Joda-time parser with instance-local default timezone

Is there an "instance-local" version of Joda's DateTimeZone.setDefault? I'm trying to achieve something like this:

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

Without polluting anything global. All I can find in the Joda docs is something that (ironically) modifies global state.

If there is a non-Joda solution, I am interested in that, too.

EDIT: Forgot to mention that if there is no ready-to-use class that does this, I'll settle for: "what is the easiest way to see if a time string contains an explicit timezone?" I can't distinguish between an explicit one and a timezone that Joda set by default.

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


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"))

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?

Need Your Help

How to create web services client with apache cxf?

java web-services soap cxf

I have followed this tutorial to create a client.

How to use SSE logical instructions

x86 sse simd

I need some help on how to use the SSE logical instructions on Visual Studio. Based on the MSDN website,