无法将字符串转换为long(timestamp)或将long转换为字符串[duplicate]

问题描述 投票:0回答:2

更大的图片是我正在编写一个使用h2数据库的junit测试。我需要比较端点返回的值并做assertequals。响应主体中的值是链接的哈希映射。键都是字符串。值可以是日期或整数,也可以是字符串或null。

我已经将期望值存储在字符串数组中。我遍历链接的哈希图中的值,并检查它是否为null,整数或日期,然后进行适当处理。日期值2020-02-03已转换为Long1580709600000。我相信日期会以某种方式转换为时间戳。我无法将其转换回最新的日期。或期望值返回时间戳。两种情况下我都异常。如何解决?感谢您的宝贵时间。enter image description here

    String values = "205,2020-02-03,Commodi";

        ResponseEntity<String> response = testRestTemplate.getForEntity(ResourceUrl, String.class);
        @SuppressWarnings("unchecked")
        List<Map<String, String>> list = objectMapper.readValue(response.getBody(), List.class);

        Iterator<Map.Entry<String, String>> it = list.get(0).entrySet().iterator();

        String expected_values[] = values.split(",", -1);
        int i = 0;

        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();

            if (expected_values[i].isEmpty())
                assertEquals(String.valueOf("null"), String.valueOf(entry.getValue()));
            else if (isInteger(expected_values[i],10))
            {
                assertEquals(Integer.valueOf(expected_values[i]), entry.getValue());
            }
            else if(isValidDate(expected_values[i]))
            {
                //long timestamp = Long.valueOf(expected_values[i].trim());
                //Long timestamp = Long.valueOf(entry.getValue().trim());
//                Timestamp ts=new Timestamp(entry.getValue());  
//                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
                Date date = new Date(Long.valueOf(entry.getValue().trim()));
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String formatedDate = format.format(date);
//                assertEquals(formatter.format(ts), entry.getValue());
                //Date date = Date.from(Instant.ofEpochMilli(Long.valueOf(entry.getValue().trim())));

            }
            else
            {
                assertEquals(expected_values[i], entry.getValue());
            }
            i++;
        }
java string junit long-integer
2个回答
1
投票

您可以将long值输入为一个对象日期作为long,然后可以使用SimpleDateFormat来应用所需的模式,参见代码beelow

Date date = new Date(Long.valueOf(entry.getValue().trim()));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String formatedDate = format.format(date);

0
投票

看此:https://www.unixtimestamp.com/index.php

您的值1580709600000似乎是一个以毫秒为单位的时间戳。并且,如果您采用这一部分1580709600(秒)并将其通过上面的链接转换为可读的日期时间,您将获得2020年3月2日上午6:00(UTC)。

此时间戳可以转换为日期:

Date date = Date.from(Instant.ofEpochMilli(1580709600000L));
© www.soinside.com 2019 - 2024. All rights reserved.