简体   繁体   中英

Java Calendar.getInstance() changing the default timezone in Linux

Please see my code as below :

SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);  
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sd.format(calendar.getTime()));

My Windows system's default time zone is EDT at this moment and time when I ran this code is (28/09/2016 12:27 PM)and when I run this code in the system the output I get as below -- which is intended (EDT to GMT Conversion) :

28/09/2016 04:00:00   

But when I run this on server (Red Hat Enterprise Linux Server release 5.11) the output I get as below :

28/09/2016 00:00:00

When I ran the below command to the Linux shell

date +%Z

It returned below output

EDT

So, I am not able to understand why the conversion did not happen. Also, I have a piece of code like below :

SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sd.format(calendar.getTime()));

Which returned below output (ran it on 28/09/2016 12:36 PM) in the same Linux Server with the intended output that is converted it to GMT

28/09/2016 16:36:46   

This code is part of a J2EE application running on WebLogic 12c. Please share if you have any clue, what might have caused the above mentioned scenario. Thanks.

You're relying on the default time zone. Specify both time zones, and the conversion should work.

28/09/2016 12:27:00 -> 28/09/2016 16:27:00 +0000

And here's some test code.

package com.ggl.testing;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimeZoneConversion {

    public static void main(String[] args) {
        SimpleDateFormat sdInput = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        sdInput.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
        SimpleDateFormat sdOutput = new SimpleDateFormat(
                "dd/MM/yyyy HH:mm:ss Z");
        sdOutput.setTimeZone(TimeZone.getTimeZone("GMT"));

        try {
            String dateString = "28/09/2016 12:27:00";
            Date inputDate = sdInput.parse(dateString);
            System.out
                    .println(dateString + " -> " + sdOutput.format(inputDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

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