具有实例本地默认时区的Joda-time解析器

时间:2015-07-08 12:18:54

标签: scala jodatime

是否存在Joda的DateTimeZone.setDefault的“实例本地”版本?我正在努力实现这样的目标:

val parser = new ParserWithDefaultTimezone("GMT+1");
parser.parse("1970-01-01 00:00:00").getMillis // -3600000L
parser.parse("1970-01-01 00:00:00 UTC").getMillis // 0L

不污染任何全球性的东西。我在Joda文档中找到的所有内容(具有讽刺意味)都会修改全局状态。

如果有非Joda解决方案,我也对此感兴趣。

编辑:忘记提及如果没有现成的类这样做,我会满足于:“查看时间字符串是否包含显式时区的最简单方法是什么?”我无法区分Joda默认设置的显式和时区。

编辑2:我没有要提供的格式字符串;我正在寻找能够在运行时推断出格式的东西。

1 个答案:

答案 0 :(得分:1)

You can use withZone to alter the date/time zone used:

val fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").withZone(DateTimeZone.forID("Europe/Berlin"))
val date = fmt.parseDateTime(???);

The set-up required to make the time zone optional is a little bit more complicated:

val tz = new DateTimeFormatterBuilder().appendLiteral(" ").appendTimeZoneId().toFormatter()
val fmt = new DateTimeFormatterBuilder()
            .append(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
            .appendOptional(tz.getParser())
            .toFormatter().withZone(DateTimeZone.forID("Europe/Berlin"))

println(fmt.parseDateTime("1970-01-01 12:00:00 UTC"))
println(fmt.parseDateTime("1970-01-01 12:00:00 Europe/Berlin"))
println(fmt.parseDateTime("1970-01-01 12:00:00"))

As long as your remark

I don't have a format string to feed; I'm looking for something that infers the format at runtime.

applies only with respect to the time zone, solution 2 might do what you want. If, on the other hand, you really don't know, in wich format the dates are provided (dd/mm/yyyy vs. mm/dd/yyyy vs. yyyy/mm/dd vs. whatever), then I think you are out of luck: such a conversion would be ambiguous at best. Is 01/03/2015 the 1st of March or the 3rd of January?