java.time
MadProgrammer的回答是正确的,尤其是关于Joda-Time的建议。Joda-Time的后继者现在作为新的Java内置到Java 8中。包的时间。下面是Java 8中的示例代码。
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
转储到控制台…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
运行时……
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
乔达时间
使用Joda-Time库(java.time的前身)的类似代码。
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
顺便说一下,输入字符串的格式是标准格式,是ISO 8601定义的几种方便的日期-时间字符串格式之一。
Joda-Time和java。在解析和生成各种日期时间值的字符串表示形式时,默认使用ISO 8601格式。