55

I am currently creating UTC DateTime objects using the current idiom

DateTime now = new DateTime(DateTimeZone.UTC);

Is there any way to default so I can create UTC-based DateTime objects using the default constructor so it is more implicit?

DateTime now = new DateTime();
algolicious
  • 1,182
  • 2
  • 10
  • 14

2 Answers2

71

If you only want to set the default timezone for joda time, use DateTimeZone.setDefault.


If you want to change the timezone that the whole jvm uses use TimeZone.setDefault method. Just be sure to set it early as it can be cached by joda time.. quoted from DateTimeZone.getDefault:

The default time zone is derived from the system property user.timezone. If that is null or is not a valid identifier, then the value of the JDK TimeZone default is converted. If that fails, UTC is used.

dacwe
  • 43,066
  • 12
  • 116
  • 140
  • 9
    note, that will affect the _whole_ jvm, which may or may not be what the OP wants. – jtahlborn Feb 22 '12 at 15:36
  • 4
    Added how to set it "only" for joda time (`DateTimeZone.setDefault`). – dacwe Feb 22 '12 at 15:41
  • 5
    I want to stress the caution by jtahlborn. `TimeZone.setDefault` affects *every thread* of *every app* running in the same JVM. Calling this method can create all kinds of confusion and unexpected behavior in other classes. – Basil Bourque Jul 23 '14 at 18:29
  • 1
    Thanks for pointing to the `DateTimeZone.setDefault`. Simplifies things to get the server behave as if it's in UTC. MongoDB would do well to make these a bit simpler. – akauppi Sep 24 '14 at 19:16
15

If you are really concerned about the extra chars, then just create a helper method:

public static DateTime newUTCDateTime() {
  return new DateTime(DateTimeZone.UTC);
}
funerr
  • 7,212
  • 14
  • 81
  • 129
jtahlborn
  • 52,909
  • 5
  • 76
  • 118