简体   繁体   中英

What is the default timezone in java.util.Date

If i create a new Date() object. What will be the default timezone it will print.

I have my machine running in GMT. And i am creating a new Date() object. If i print why does it shows Thu Jul 05 08:21:05 PKT 2012. How does it takes the timezone as PKT ?

The date itself doesn't have any time zone. Its toString() method uses the current default time zone to return a String representing this date:

Date date = new Date();

System.out.println(TimeZone.getDefault());
System.out.println(date);

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

System.out.println(TimeZone.getDefault());
System.out.println(date);

Executing the above code on my machine leads to the following output:

sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
Fri Jul 06 09:24:45 CEST 2012
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Fri Jul 06 07:24:45 UTC 2012

Well actually basic date times usually are time zone agnostic, they don't store time zones. To make use of time zone you use formatters, calendars and the like. Of course the basic date has to be in a default time zone, whatever it might be (usually GMT), otherwise you wouldn't be able to create a local date from the basic date instance.

In you particular case it would help to look into a) the javadocs and b) into the class itself, since JDK is usually distributed with source code of java.util.Date. According to javadoc the java.util.Date class represents number of milliseconds since the standard base time known as "the epoch", namely 1 January 1970, 00:00:00 GMT.

If it shows a different date when printed on your machine, it is because your system will print it using time zone default for your system. You can however print it yourself using any other time zone.

If you are running under linux, there is some magic timezone file somewhere in the system. For my gentoo the magic was just creating a text file /etc/timezone with content

Europe/Berlin

The funny thing is that date gave the correct time and timezone (CEST) all the time, but java sent me to Greenwhich.

> date
Thu Sep 18 08:49:14 CEST 2014

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM