Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java.util.Date is giving me wrong time?

Tags:

java

date

System.out.println(new Date());

Thu Feb 23 04:57:57 ACT 2012

I am running it in a main method. And my system current time is PKT. But it's giving me ACT time.

Any idea? How to get correct system's time?

enter image description here

like image 435
Tahir Avatar asked Feb 23 '12 10:02

Tahir


People also ask

What is wrong with Java Util date?

util. Date (just Date from now on) is a terrible type, which explains why so much of it was deprecated in Java 1.1 (but is still being used, unfortunately). Design flaws include: Its name is misleading: it doesn't represent a Date , it represents an instant in time.

How do I change the TimeZone in Java Util date?

You can make use of the following DateFormat. SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); myDate. setTimeZone(TimeZone. getTimeZone("UTC")); Date newDate = myDate.

Is Java Util date UTC?

java. util. Date has no specific time zone, although its value is most commonly thought of in relation to UTC.


1 Answers

The problem appears to be with the time zone, not the Date value itself. So instead of printing out the current date, use something like this to print out the current time zone:

import java.util.TimeZone ;

public class Test {
    public static void main(String[] args) throws Exception {
        TimeZone zone = TimeZone.getDefault();
        System.out.println(zone.getDisplayName());
        System.out.println(zone.getID());
    }
}

For example, for me that prints:

Greenwich Mean Time
Europe/London

Once you know more details about what Java thinks your default time zone is, you can start looking for why it thinks that. Is there anything about how you're running Java which is non-standard? Any environment variables which look suspiciously like the incorrect time zone?

You might also want to print out the following system properties, which are used when determining the time zone:

user.timezone
user.country
java.home

(Print them out before getting the default time zone - user.timezone is set as part of fetching it, if it wasn't set before.)

like image 124
Jon Skeet Avatar answered Sep 19 '22 08:09

Jon Skeet