Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date and time conversion to some other Timezone in java

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::

The current time in India is :: Fri Feb 24 16:09:23 IST 2012

The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012

And the actual Time according to CST time zone is ::

Friday, 24 February 4:39:16 a.m(GMT - 6:00)

So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::

package MyPackage;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Temp2 {


    public static void main(String[] args) {

        try {
            Calendar currentdate = Calendar.getInstance();
            String strdate = null;
            DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            strdate = formatter.format(currentdate.getTime());
            TimeZone obj = TimeZone.getTimeZone("CST");

            formatter.setTimeZone(obj);
            //System.out.println(strdate);
            //System.out.println(formatter.parse(strdate));
            Date theResult = formatter.parse(strdate);

            System.out.println("The current time in India is  :: " +currentdate.getTime());

            System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
        } catch (ParseException e) {
           e.printStackTrace();
        }
    }
}
like image 894
Shantanu Tomar Avatar asked Feb 24 '12 10:02

Shantanu Tomar


2 Answers

First message, don’t handle your date and time as strings in your code. Just as you don’t handle numbers and Boolean values as strings (I hope). Use proper date-time objects.

java.time

Sometimes we get date and time as string input. It may be from a text file, from the user or from data exchange with another system, for example. In those cases parse into a proper date-time object first thing. Second message, use java.time, the modern Java date and time API, for your date and time work.

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

    String input = "2015-11-01 01:00:00";

    ZonedDateTime nyTime = LocalDateTime.parse(input, formatter)
            .atZone(ZoneId.of("America/New_York"));
    System.out.println("Time in New York: " + nyTime);

Output from this snippet is:

Time in New York: 2015-11-01T01:00-04:00[America/New_York]

To convert to GMT:

    OffsetDateTime gmtTime = nyTime.toOffsetDateTime()
            .withOffsetSameInstant(ZoneOffset.UTC);
    System.out.println("GMT Time: " + gmtTime);
GMT Time: 2015-11-01T05:00Z

If you need to give string output, format using a date-time formatter. Here’s an example of formatting for an American audience:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                    .withLocale(Locale.US);
    String formattedDateTime = gmtTime.format(userFormatter);
    System.out.println("GMT Time formatted for user: " + formattedDateTime);
GMT Time formatted for user: Nov 1, 2015, 5:00:00 AM

You additionally asked:

Between the two results below, which one should you take?

I understand that you ask because both are valid answers. On November 1, 2015 summer time (DST) ended at 2 AM. That is, after 01:59:59 came 01:00:00 a second time. So when we have got 2015-11-01 01:00:00 as input, it is ambiguous. It could be in Eastern Daylight Time, equal to 05:00 GMT, or it could be in Eastern Standard Time, one hour later, hence equal to 06:00 GMT. There is no way that I can tell you which of them is correct in your case. You may control which result you get using withEarlierOffsetAtOverlap() or withLaterOffsetAtOverlap(). Above we got the DST interpretation. So to get the standard time interpretation:

    nyTime = nyTime.withLaterOffsetAtOverlap();
    System.out.println("Alternate time in New York: " + nyTime);

Alternate time in New York: 2015-11-01T01:00-05:00[America/New_York]

We notice that the hour of day is still 01:00, but the offset is now -05:00 instead of -04:00. This also gives us a different GMT time:

GMT Time: 2015-11-01T06:00Z
GMT Time formatted for user: Nov 1, 2015, 6:00:00 AM

Avoid SimpleDateFormat and friends

While the other answers are generally correct, the classes DateFormat, SimpleDateFormat, Date and Calendar used there are poorly designed and long outdated. The first two are particularly troublesome. I recommend you avoid all of them. I frankly find the modern API so much nicer to work with.

Link

Oracle tutorial: Date Time explaining how to use java.time.

like image 144
Ole V.V. Avatar answered Sep 30 '22 14:09

Ole V.V.


It's over the web. Could have googled. Anyways, here is a version for you (shamelessly picked and modified from here):

Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");

calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
    calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}

calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
    calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}

System.out.println(calendar.getTime());
like image 25
Nishant Avatar answered Sep 30 '22 14:09

Nishant