pc_ pc_ - 1 year ago 137
Java Question

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);

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


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();

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.

Answer Source

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");
        SimpleDateFormat sdOutput = new SimpleDateFormat(
                "dd/MM/yyyy HH:mm:ss Z");

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download