基于区域设置的Joda-Time DateTime格式 [英] Joda-Time DateTime formatting based on locale
问题描述
我从另一个系统收到字符串日期,我知道该日期的区域设置(也可从其他系统获得)。我想将此字符串转换为 Joda-time DateTime 对象,而不显式指定目标模式。
I receive a string date from another system and I know the locale of that date (also available from the other system). I want to convert this String into a Joda-Time DateTime object without explicitly specifying the target pattern.
所以例如,我想将这个String09/29/2014转换成一个日期对象,只使用区域设置,而不是将日期格式硬编码为 mm / dd / yyyy。我不能硬编码格式,因为这将取决于我收到的日期的本地。
So for example, I want to convert this String "09/29/2014" into a date object using the locale only and not by hard coding the date format to "mm/dd/yyyy". I cant hard code the format as this will vary depending on the local of the date I receive.
推荐答案
String localizedCalendarDate = DateTimeFormat.shortDate().print(new LocalDate(2014, 9, 29));
// uses in Germany: dd.MM.yyyy
// but uses in US: MM/dd/yyyy
LocalDate date =
DateTimeFormat.mediumDate().withLocale(Locale.US).parseLocalDate("09/29/2014");
DateTime dt = date.toDateTimeAtStartOfDay(DateTimeZone.forID("America/Los_Angeles"));
正如你所看到的,你还需要知道时钟时间(=例子中的开始) )和时区(例如美国加州),以便将解析日期转换为全局时间戳,如 DateTime
。
As you can see, you will also need to know the clock time (= start of day in example) and time zone (US-California in example) in order to convert a parsed date to a global timestamp like DateTime
.
这篇关于基于区域设置的Joda-Time DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!