小编典典
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日?
您可以 猜测 是否愿意,尽管根据准确度对您的业务问题的重要性可能不明智。
您可以使用字符串长度来帮助指导猜测。
List < DateTimeFormatter > dateFormatters = new ArrayList <>( 2 );
dateFormatters.add( DateTimeFormatter.ofPattern( "uuuu-MM-dd" ) ); // BEWARE of ambiguity in these formatters regarding month-versus-day.
dateFormatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) );
String input = "1990-02-07";
// String input = "12-02-1990" ;
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 )
{
// No code here.
// We purposely ignore this exception, moving on to try the next formatter in our list.
}
}
} else if ( ( input.length() > 10 ) && input.substring( input.length() - 1 ).equalsIgnoreCase( "Z" ) ) // If over 10 in length AND ends in a Z.
{
Instant ld = null;
try
{
ld = Instant.parse( input ); // Uses `DateTimeFormatter.ISO_INSTANT` formatter.
} catch ( Exception e )
{
throw new IllegalArgumentException( "Unable to parse date-time string argument. Message # 0d10425f-42f3-4e58-9baa-84ff949e9574." );
}
} else if ( input.length() > 10 )
{
// TODO: Define another list of formatters to try here.
} 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 // Impossible-to-reach, for defensive programming.
{
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
要了解更多信息,请参见Oracle教程 。并在Stack
Overflow中搜索许多示例和说明。规格为JSR 310。
您可以直接与数据库交换 java.time 对象。使用与JDBC
4.2或更高版本兼容的JDBC驱动程序。不需要字符串,不需要类。java.sql.*
在哪里获取java.time类?
Java SE 8 ,Java SE 9 和更高版本 内置的
标准Java API的一部分,具有捆绑的实现。
Java 9添加了一些次要功能和修复。
Java SE 6 和Java SE 7java.time的许多功能在ThreeTen- Backport中都被反向移植到Java 6和7 。
安卓系统更高版本的Android捆绑了java.time类的实现。
对于早期的Android(<26),ThreeTenABP 项目改编了 ThreeTen-Backport (如上所述)。请参阅如何使用ThreeTenABP… 。
该ThreeTen-额外
项目与其他类扩展java.time。该项目是将来可能向java.time添加内容的试验场。你可能在这里找到一些有用的类,比如Interval,YearWeek,YearQuarter,和更多。
2020-10-16