Convert date string from ISO 8601 format to another(将日期字符串从ISO 8601格式转换为另一种格式)
问题描述
我有这段代码,我在其中尝试将日期字符串从一种格式转换为另一种格式,最后我希望再次使用Date对象。
String dateString = "2014-10-04";
SimpleDateFormat oldFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = oldFormatter.parse(dateString);
SimpleDateFormat newFormatter = new SimpleDateFormat("dd-MMM-yyyy");
String convertDateStr = newFormatter.format(parsedDate);
Date convertedDate = newFormatter.parse(convertDateStr);
当我使用日期字符串值为"2014-10-04"测试上述代码时,上述代码可以正常执行,但转换日期格式更改为"Sat Oct 04 00:00:00 IST 2014",而不是"dd-MMM-yyyy"格式。
我有这样的功能:我有两个不同格式的日期,比较时需要得到剩余天数的差异,所以我需要先将一个日期格式转换为其他日期,然后才能得到天数的差异。
编辑-是否有将日期字符串转换为指定格式并以转换后的格式取回日期对象的替代选项
推荐答案
tl;dr
LocalDate.parse( // Represent a date-only value with a date-only class.
"2014-10-04" // Inputs in standard ISO 8601 format are parsed by default. No need to specify a formatting pattern.
) // Returns a `LocalDate` object. Do not conflate a date-time object with a String that represents its value. A `LocalDate` has no "format".
.format( // Generate a String representing the `LocalDate` object’s value.
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) // Define your custom formatting pattern. Specify `Locale` for human language and cultural norms used in localization.
) // Return a String.
java.time
现代方法使用java.time类,这些类取代了麻烦的旧旧日期-时间类,如Date
/Calendar
/SimpleDateFormat
。
将仅日期类用于仅日期值,而不是日期+时间类。LocalDate
类表示不带时间和时区的仅日期值。
您的输入字符串恰好符合标准ISO 8601格式。在分析/生成字符串时,java.time类默认使用ISO 8601格式。因此无需指定格式模式。
String input = "2014-10-04" ;
LocalDate ld = LocalDate.parse( input ) ; // No need to specify a formatting pattern for ISO 8601 inputs.
要生成以特定格式表示LocalDate
对象的值的字符串,请定义格式化模式。指定Locale
对象以确定本地化中使用的人类语言和文化规范。
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , locale ) ;
String output = ld.format( f ) ;
2014年10月4日
关于java.time
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期-时间类,如java.util.Date
、Calendar
、&;SimpleDateFormat
。
Joda-Time项目现在位于maintenance mode中,建议迁移到java.time类。
要了解更多信息,请参阅Oracle Tutorial。和搜索堆栈溢出以获取许多示例和解释。规范为JSR 310。您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC driver。不需要字符串,也不需要java.sql.*
个类。
从哪里获取java.time类?
- Java SE 8、Java SE 9和更高
- 内置。
- 带有捆绑实现的标准Java API的一部分。
- Java 9添加了一些次要功能和修复。
- Java SE 6和Java SE 7
- 许多java.time功能已在ThreeTen-Backport中重新移植到Java 6&;7。
- Android
- 更高版本的Android捆绑实现的java.time类。
- 对于更早版本的Android(<;26),ThreeTenABP项目适配ThreeTen-Backport(如上所述)。请参阅How to use ThreeTenABP…。
ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能添加到java.time中提供了一个试验场。您可以在此处找到一些有用的类,如Interval
、YearWeek
、YearQuarter
和more。
这篇关于将日期字符串从ISO 8601格式转换为另一种格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!