我正在尝试使用Joda时间库将String
日期和时间转换为Date
,但得到的结果不是预期的。
从服务器我得到:
2017年11月8日12:30
2017年10月11日12:30
Joda将其转换为:
2017-01-08T12:30:00.000+02:00
2017-01-10T12:00.000+02:000
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/mm/yyyy HH:mm:ss");
// add two :00 at the end for the seconds
startDate = startDate +":00";
DateTime start = formatter.parseDateTime(startDate);
System.out.println(start.toString());
endDate= endDate + ":00";
DateTime end = formatter.parseDateTime(endDate);
这是因为您使用的是当月的mm
,但正确的模式是大写MM
。查看文档以了解更多详细信息。
还有一件事。如果您的输入没有秒(:00
),则不需要将其附加在输入字符串的末尾。你可以简单地创建一个没有它的模式:
// "MM" for month, and don't use "ss" for seconds if input doesn't have it
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
// parse input (without ":00" for the seconds)
DateTime start = formatter.parseDateTime("08/11/2017 12:30");
System.out.println(start.toString());
输出为:
2017-11-08T12:30:00.000-02:00
请注意,偏移量(-02:00
)与您的偏移量不同。这是因为如果不指定默认时区,DateTime
将使用默认时区。