Question

Before anybody downvotes this question, I have browsed the web and StackOverflow for the situation that I am facing and did not find anything, hence I am posting as a new question.

I have a situation with java date and timezones.

Situation:

There are 2 servers on 2 different timezones, lets say PST and CST. I am receiving dateString(date as a string) from those servers. But, when I try to convert the string back to date, using SimpleDateFormat, the date information(Year, month, day, hours, minutes, seconds) is being converted properly. But the timezone information is not being preserved.

If I run my code on a server in EST, the pstDateString is converted to Date format, but the Timezone is being set to EDT, instead of PST.

I thought about it in many different ways but may be that I am stressed, I am not able to find a solution. Any help ?

Code block that would simulate the situation :

        DateFormat outDF1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        outDF1.setTimeZone(TimeZone.getTimeZone("PST"));        
        String pstDateString = outDF1.format(new Date());

        DateFormat outDF2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        outDF2.setTimeZone(TimeZone.getTimeZone("CST"));
        String cstDateString = outDF2.format(new Date());

        System.out.println("pstDateString "+pstDateString);
        System.out.println("cstDateString "+cstDateString);

        Date cstDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").parse(cstDateString);
        Date pstDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").parse(pstDateString);

        System.out.println("Date after format from string: "+pstDate);
        System.out.println("Date after format from string: "+cstDate);

Output Currently:

pstDateString 2012-06-07 10:26:689
cstDateString 2012-06-07 12:26:694
Date after format from string: Thu Jun 07 10:26:00 EDT 2012
Date after format from string: Thu Jun 07 12:26:00 EDT 2012

Output Expected:

pstDateString 2012-06-07 10:26:689
cstDateString 2012-06-07 12:26:694
Date after format from string: Thu Jun 07 10:26:00 PST 2012
Date after format from string: Thu Jun 07 12:26:00 CST 2012
Was it helpful?

Solution

the java.util.Date class has no timezone, it is always in UTC. if you want to preserve the incoming timezone, you will need a new class which combines a Date and a TimeZone. you could create a simple holder class, or possibly use a Calendar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top