java DateTimeFormatterBuilder在测试时间失败 [英] java DateTimeFormatterBuilder fails on testtime

查看:116
本文介绍了java DateTimeFormatterBuilder在测试时间失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对DateTimeFormatterBuilder有一个简单的jUnit测试. 在运行时,当某些String出现在Spring-MVC hanlder(@RequestParam)

I have a simple jUnit test for DateTimeFormatterBuilder. At runtime it works, when some String comes on Spring-MVC hanlder (@RequestParam)

在测试时,它失败并显示相同的String值.

At testtime it fails with the same String value.

测试值:25-May-2018 11:10

要测试的方法:

public void getTimeDifference(@RequestParam String startDate, @RequestParam String endDate) {
    DateTimeFormatter DATE_TIME_FORMAT = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yyyy HH:mm").toFormatter();
    LocalDateTime.parse(startDate,DATE_TIME_FORMAT);
    return   messages;
}

测试方法:

@Test
public void testFormat() throws Exception {
    final String startDateFormatA = "25-May-2018 11:10";
    final String endDateFormatA = "25-May-2018 11:10";
    assertEquals("06:00", callDbController.getTimeDifference(startDateFormatA, endDateFormatA)[1]);
}

我的测试:在运行时,我设置一个断点并在Display-View上对其进行测试:

My Test: At runtime I set a break-point and test it on Display-View:

LocalDateTime.parse("25-May-2018 11:10",DATE_TIME_FORMAT)

在具有相同spring-aplication-context的测试时,我像在运行时一样进行操作,但是失败.

At testtime with the same spring-aplication-context I do the same like on runtime and it fails.

任何人都有想法吗?

推荐答案

您正在使用hh,即 clock-hour-of-am-pm(1-12) ,而未添加AM /PM信息在日期字符串中.

You are using hh which is clock-hour-of-am-pm (1-12) without adding the AM/PM information in the date string.

相反,您应使用每小时(0-23),如以下模式:DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z");

Instead you should use of hour-of-day (0-23) like the pattern: DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z");

或者您可以在日期模式中添加a:
DateTimeFormatter.ofPattern("dd/MMM/yyyy:hh:mm:ss a Z");

Or you can add the a in the date pattern:
DateTimeFormatter.ofPattern("dd/MMM/yyyy:hh:mm:ss a Z");

并在日期字符串中传递AM/PM信息:

and pass the AM/PM information in the date string:

"20/Mar/2019:00:00:01 AM +0100"

编辑:

根据评论,问题也可能与您使用的语言环境有关,为了使用en/US语言环境,只需将语言环境传递给ofPattern方法:

As per the comments, the issue could also be with the locale you are using, in order to use the en/US locale just pass the locale to the ofPattern method:

 Locale locale = new Locale("en", "US");
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", locale); 

但是您仍然需要将 clock-of-am-pm (hh)更改为 hour-of-day (HH).

But you still need to correct the clock-hour-of-am-pm (hh) to hour-of-day (HH).

这篇关于java DateTimeFormatterBuilder在测试时间失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆