Defaulting date time zone to UTC for Jodatime's DateTime

JavaJodatime

Java Problem Overview


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();

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

public static DateTime newUTCDateTime() {
  return new DateTime(DateTimeZone.UTC);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalgoliciousView Question on Stackoverflow
Solution 1 - JavadacweView Answer on Stackoverflow
Solution 2 - JavajtahlbornView Answer on Stackoverflow