Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What time zone does Date.toString() display?

By default, what time zone does method java.util.Date.toString() display? Since a Java Date stores a given date in UTC and doesn't contain any explicit time zone, does Date.toString() simply display the default time zone for the host, or TimeZone.getDefault()?

like image 489
Derek Mahar Avatar asked Nov 16 '10 21:11

Derek Mahar


2 Answers

It displays using TimeZone.getDefault() which, in turn, will default to the time zone of the operating system it is running on (i.e. the host). So in practice, they will be the same thing

Note that a Java date is not really a date! It is an instant in time, represented by a millisecond offset since the beginning of the epoch. It still contains methods which reference year, month etc but these are all deprecated. You should on no account be using a Date object as if it were a date.

Use a Calendar (although this is arguably even more broken than Date) or a decent library like JODA.

like image 63
oxbow_lakes Avatar answered Nov 18 '22 16:11

oxbow_lakes


Does it display the default time zone for the host, or TimeZone.getDefault()?

The latter (which is the same as the former unless you set it explicitly somewhere). However, this is information gleamed from the source code, so it should be considered an implementation detail. If you want specific repeatable behavior, you should implement it yourself.

like image 42
Michael Borgwardt Avatar answered Nov 18 '22 14:11

Michael Borgwardt