简体   繁体   English

将日期字符串转换为Joda-Time中的datetime对象?

[英]Convert date string to datetime object in Joda-Time?

I have a date string similar to: 我有一个类似于以下内容的日期字符串:

"2014-04-10T00:00:00.000" “ 2014-04-10T00:00:00.000”

So I need to convert this to a Joda-Time DateTime object. 因此,我需要将其转换为Joda-Time DateTime对象。

Here is my code : 这是我的代码:

String datePattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern);

currentCard.setStartDate("2014-04-10T00:00:00.000");
currentCard.setEndDate("2015-04-10T00:00:00.000");

DateTime startDateTime = dateFormatter.parseDateTime(currentCard.getStartDate());
DateTime endDateTime = dateFormatter.parseDateTime(currentCard.getEndDate());

if (startDateTime.isBeforeNow() && endDateTime.isAfterNow()) {
    currentCard.setActive(true);
} else {
    currentCard.setActive(false);
}

It tells me string is too short 告诉我string is too short

I believe the correct syntax for the date pattern is "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" . 我相信日期模式的正确语法是"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" That way the Z is literally used. 这样, Z就会被字面地使用。

While the other answers are correct, both the answers and your question are working too hard. 当其他答案正确时,答案和您的问题都太努力了。

ISO 8601 Format ISO 8601格式

The format of the string in question, "2014-04-10T00:00:00.000", is standard ISO 8601 format. 有问题的字符串格式“ 2014-04-10T00:00:00.000”是标准的ISO 8601格式。 The DateTime class in Joda-Time has a built-in ISO 8601 parser/formatter built-in, used by default. Joda-Time中的DateTime类具有内置的内置ISO 8601解析器/格式器,默认情况下使用。 So no need to instantiate a formatter. 因此,无需实例化格式化程序。 Merely pass the string to the constructor of DateTime . 仅将字符串传递给DateTime的构造函数。

Time Zone 时区

Specify a time zone by which to interpret that date-time value. 指定用于解释该日期时间值的时区。 Otherwise the JVM's current default time zone is applied. 否则,将应用JVM的当前默认时区。

Example: 例:

DateTimeZone timeZoneMontréal = DateTimeZone.forID( "America/Montreal" );

Example Code 范例程式码

Some example code using Joda-Time 2.5. 一些使用Joda-Time 2.5的示例代码。

DateTime dateTime = new DateTime( "2014-04-10T00:00:00.000", DateTimeZone.UTC );

If that string represented a wall-time† moment in Québec rather than UTC , then specify that time zone by which the string should be understood while parsing. 如果该字符串表示魁北克的墙时时刻,而不是UTC ,则指定在解析时应理解该字符串的时区。

DateTime dateTime = new DateTime( "2014-04-10T00:00:00.000", timeZoneMontréal );

Specify Format 指定格式

As per the comment by Meno Hochschild , you may prefer to specify the expected format of the incoming String. 根据Meno Hochschild的评论,您可能希望指定传入String的预期格式。 Joda-Time has many pre-defined formatters built-in, as well as permitting you to define your own. Joda-Time内置了许多预定义的格式化程序 ,并且允许您定义自己的格式化程序 In this case, our string lacks a time zone offset at the end, so we specify the formatter known as dateHourMinuteSecondFraction . 在这种情况下,我们的字符串末尾没有时区偏移,因此我们指定了称为dateHourMinuteSecondFraction的格式化程序。

What if the incoming string is malformed or using an unexpected format? 如果输入的字符串格式错误或使用意外格式怎么办? An exception is thrown. 引发异常。 For robust code, trap for that exception. 对于健壮的代码,请捕获该异常。

String input = "2014-04-10T00:00:00.000";
DateTimeZone timeZoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecondFraction().withZone( timeZoneMontréal );
DateTime dateTime = null;
try {
    dateTime = formatter.parseDateTime( input );
} catch ( IllegalArgumentException e ) {
    System.out.println( "Unexpected format of incoming date-time string: " + input + ". Exception: " + e ); // Handle exception for bad input.
}

Adjust to UTC for comparison. 调整至UTC进行比较。

DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );

Dump to console. 转储到控制台。

System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );

When run. 运行时。

dateTime: 2014-04-10T00:00:00.000-04:00
dateTimeUtc: 2014-04-10T04:00:00.000Z

† Wall-Time = The time as usually seen on some clock on some wall in some locality. †Wall-Time =在某些地方的某些墙上的某个时钟上通常看到的时间。

Regarding your first edit using the pattern "yyyy-MM-dd'T'HH:mm:ss.SSSZ" and experiencing a parse problem with Z-input, it is obviously a version problem , see here: 关于使用模式“ yyyy-MM-dd'T'HH:mm:ss.SSSZ”的第一次编辑并遇到Z输入的解析问题,显然是版本问题 ,请参见此处:

On Joda-Time-release-notes for change 1.6 to 2.0 => Joda-Time-release-notes上将1.6更改为2.0 =>

"Allow 'Z' and 'ZZ' in format patterns to parse 'Z' as '+00:00' [2827359]" “允许格式格式中的“ Z”和“ ZZ”将“ Z”解析为“ +00:00” [2827359]”

So the solution is to use the newest version of Joda-Time. 因此解决方案是使用最新版本的Joda-Time。 Note that the use of the pattern symbol Z is more powerful than just to use a literal 'Z' in pattern expression because any ISO-8601-compatible string might not only contain "Z" at the end but also offsets like "+0200". 请注意,使用模式符号Z不仅比在模式表达式中使用文字'Z'更强大,因为任何与ISO-8601兼容的字符串不仅可能在结尾处包含“ Z”,而且还会出现诸如“ +0200”的偏移量。 And if the offset might contain a colon (example "+05:30") then you should use the double ZZ in your pattern. 并且,如果偏移量可能包含冒号(例如“ +05:30”),则应在模式中使用双ZZ。

Comment about your edit to remove the pattern symbol Z: 评论有关您删除图案符号Z的编辑:

In that case I do not see any exception with version 2.1. 在那种情况下,我看不到2.1版有任何异常。 Joda-Time will just interprete the input as local time in system timezone and add the appropriate timezone offset. Joda-Time只会将输入解释为系统时区中的本地时间,并添加适当的时区偏移量。 Anyway, you have to adapt your pattern to expected inputs, not otherwise around. 无论如何,您必须使模式适应预期的输入,而不是其他情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Joda-Time将字符串日期时间转换为另一种格式 - Joda-Time Convert String Date Time to Another Format 使用joda-time将字符串转换为日期时发生IllegalArgumentException - IllegalArgumentException when using joda-time to convert string to date 将 Joda-Time DateTime 格式化为字符串 - Formatting Joda-Time DateTime to String 将Joda-Time DateTime - ISO 8601格式日期转换为其他日期格式 - Convert Joda-Time DateTime - ISO 8601 format date to another date format 用时区将Joda-Time`DateTime`转换为没有时区的DateTime? - Convert Joda-Time `DateTime` with timezone to DateTime without timezone? 如何将Joda-Time DateTime转换为java.util.Date,反之亦然? - How to convert Joda-Time DateTime to java.util.Date and vice versa? Java:使用joda-time向DateTime对象添加45天会产生荒谬的日期 - Java: Adding 45 days to a DateTime object using joda-time produces a nonsensical date 使用Joda-Time Library将字符串转换为Google Tasks API中的DateTime格式 - Using Joda-Time Library to Convert String to DateTime Format in Google Tasks API 在JDO / DataNucleus中,我可以查询Joda-Time DateTime对象吗? - In JDO/DataNucleus can I query for a Joda-Time DateTime object? 什么是持久化Joda-Time`DateTime`对象的最有效方法? - Whats the most efficient way to persist a Joda-Time `DateTime` object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM