在发布之前,您应该费心做一些搜索。StackOverflow.com 已经有很多这样的问题和答案。
但为了后代,这里有一些使用Joda-Time 2.3 库的示例代码。避免与 Java 捆绑在一起的 java.util.Date/Calendar 类,因为它们的设计和实现都很糟糕。在 Java 8 中,继续使用 Joda-Time 或切换到JSR 310: Date and Time API定义的新java.time.* 类。这些新课程的灵感来自 Joda-Time,但完全重新设计。
Joda-Time 有许多旨在格式化输出的功能。Joda-Time 提供内置标准 (ISO 8601) 格式。某些类以适合主机区域设置的格式和语言呈现字符串,或者您可以指定区域设置。Joda-Time 还允许您定义自己的时髦格式。搜索“joda”+“format”会得到很多例子。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String input = "05/27/2014" + " " + "23:01";
解析那个字符串……</p>
// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );
理想情况下,您可以将值以适当的日期时间格式存储在数据库中。如果不可能,则以 ISO 8601格式存储为字符串,设置为UTC /GMT(无时区偏移)。
// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.
通常在 UTC 中执行您的业务逻辑和存储。仅在应用的用户界面部分切换到本地时区和本地化格式。
// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );
转储到控制台...</p>
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );
运行时……</p>
input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM