What is the default timezone in java.util.Date

2019-01-09 01:28发布

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 ?

3条回答
Emotional °昔
2楼-- · 2019-01-09 01:37

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.

查看更多
贼婆χ
3楼-- · 2019-01-09 01:43

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
查看更多
成全新的幸福
4楼-- · 2019-01-09 02:00

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
查看更多
登录 后发表回答