ISO 8601
现在的问题是所有联系人都有不同的生日格式。
这才是真正的问题:以各种格式存储日期时间值。
在将日期时间值序列化为文本时,始终使用标准的ISO 8601格式。这些格式明智而实用,避免歧义,易于机器解析,也易于跨文化人类阅读。
java.time类在解析/生成字符串时默认使用这些标准格式。
java.time
现代方法使用
java.time类替代了麻烦的旧日期时间类。避免使用旧的
Date
、
Calendar
、
SimpleDateFormat
和相关类。
例如,一个同步联系人的生日可能是"1990-02-07"或"1988-06-15T22:00:00.000Z"或"12-02-1990"等...
由于歧义,解析
任何可能的日期时间格式都是不可能的。例如,
01-02-1990
表示1月2日还是2月1日?
您可以进行
猜测,但这可能是不明智的,具体取决于准确性对您的业务问题有多重要。
使用
DateTimeFormatter
定义一堆格式化模式。尝试每个模式。当抛出
DateTimeParseException
时,继续下一个模式,直到找到一个可用的。
你可以使用
string length来帮助指导猜测。
List < DateTimeFormatter > dateFormatters = new ArrayList <>( 2 );
dateFormatters.add( DateTimeFormatter.ofPattern( "uuuu-MM-dd" ) );
dateFormatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) );
String input = "1990-02-07";
if ( null == input )
{
throw new IllegalArgumentException( "Passed null argument where a date-time string is expected. Message # c7a4fe0e-9500-45d5-a041-74d457381008." );
} else if ( input.length() <= 10 )
{
LocalDate ld = null;
for ( DateTimeFormatter f : dateFormatters )
{
try
{
ld = LocalDate.parse( input , f );
System.out.println( ld );
} catch ( Exception e )
{
}
}
} else if ( ( input.length() > 10 ) && input.substring( input.length() - 1 ).equalsIgnoreCase( "Z" ) )
{
Instant ld = null;
try
{
ld = Instant.parse( input );
} catch ( Exception e )
{
throw new IllegalArgumentException( "Unable to parse date-time string argument. Message # 0d10425f-42f3-4e58-9baa-84ff949e9574." );
}
} else if ( input.length() > 10 )
{
} else if ( input.length() == 0 )
{
throw new IllegalArgumentException( "Passed empty string where a date-time string is expected. Message # 0ffbd9b6-8905-4e28-a732-0f402d4673df." );
} else
{
throw new RuntimeException( "ERROR - Unexpectedly reached IF-ELSE when checking input argument. Message # 6228d9e0-047a-4b83-8916-bc526e0fd22d." );
}
System.out.println("Done running.");
1990年02月07日
完成运行。
关于java.time
java.time框架内置于Java 8及更高版本中。这些类替代了老旧的遗留日期时间类,例如java.util.Date
、Calendar
和SimpleDateFormat
。
Joda-Time项目现在处于维护模式,建议迁移到java.time类。
想要了解更多,请查看Oracle教程。并且在Stack Overflow上搜索许多示例和解释。规范为JSR 310。
您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC驱动程序。无需字符串,也不需要java.sql.*
类。
如何获取java.time类?
ThreeTen-Extra项目通过增加类来扩展java.time。该项目是java.time可能未来添加的一些内容的试验场。您可能会在这里找到一些有用的类,例如Interval
, YearWeek
, YearQuarter
和更多。