Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defaulting date time zone to UTC for Jodatime's DateTime

Tags:

java

jodatime

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(); 
like image 600
algolicious Avatar asked Feb 22 '12 15:02

algolicious


People also ask

Does Joda DateTime have timezone?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.

Why use joda-time?

Joda-Time makes it easy for us to work with different time zones and changed between them. We have the DateTimeZone abstract class which is used to represent all aspects regarding a time zone.

Does timezone affect date?

Timezones only affect the human readable representation of the point in time. are both the exact same point in absolute time. It's just two different human ways of describing the same instant.


2 Answers

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.

like image 62
dacwe Avatar answered Sep 27 '22 20:09

dacwe


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

public static DateTime newUTCDateTime() {   return new DateTime(DateTimeZone.UTC); } 
like image 29
jtahlborn Avatar answered Sep 27 '22 19:09

jtahlborn