Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar.getTime() not returning UTC date if TimeZone is defined

I have done this for my Calendar instance to return Date in UTC timezone:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS Z");
TimeZone tz = TimeZoneUtil.getTimeZone(StringPool.UTC);
formatter.setTimeZone(tz);

    Date dtStart = null;
    Date dtEnd = null;

    try{
        dtStart = formatter.parse(formatter.format(startDate.getTime()));
        dtEnd = formatter.parse(formatter.format(endDate.getTime()));
    }catch (Exception e) {
        e.getStackTrace();
}

It works fine till I format calendar timestamp to return a string date with required timezone but when I parse that string date to Date date, it again picks up local timezone? I need to store Date object in UTC timezone.

Any help will be highly appreciated!

like image 279
Parkash Kumar Avatar asked Jun 21 '13 11:06

Parkash Kumar


People also ask

Does getTime return UTC?

When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch). The getTime() always uses UTC for time representation.

How do I set timezone in calendar instance?

Calendar setTimeZone() Method in Java with ExamplesThe setTimeZone(TimeZone time_zone) method in Calendar class takes a Time Zone value as a parameter and modifies or set the timezone represented by this Calendar.

How do I create a UTC timestamp in Java?

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); f. setTimeZone(TimeZone. getTimeZone("UTC")); System. out.


1 Answers

You can use this:

 Date localTime = new Date(); 

 //creating DateFormat for converting time from local timezone to GMT
 DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");

 //getting GMT timezone, you can get any timezone e.g. UTC
 converter.setTimeZone(TimeZone.getTimeZone("GMT"));

 System.out.println("local time : " + localTime);;
 System.out.println("time in GMT : " + converter.format(localTime));

It will give:
local time: Fri Jun 21 11:55:00 UTC 2013
time in GMT : 21/06/2013:11:55:00

I hope it will help.

Cheers.

like image 81
Vahe Avatar answered Nov 04 '22 06:11

Vahe