Question

In my application, I need to create a Gregorian Calender object using the date, time and time zone objects. I happen to have all data in string/int format viz: DD, MM, YY, HH, SS, XXX .

E.g. 20 , 03 , 14 , 09 , 30 , PST

Can I create a calender object using all the above parameters ??

I tried using java Calender

Calendar calendar = new GregorianCalendar(14 , 02 , 20 , 9 , 30 , 00);
calendar.setTimeZone(TimeZone.getTimeZone("PST"));

but it doesn't allow me to use timezone and always picks up my server timezone (EDT). So I always end up with : Thu Mar 20 09:30:00 EDT 2014

What I actually need is : Thu Mar 20 09:30:00 PST 2014

Was it helpful?

Solution

There are several issues. First you should use as year 2014, not just 14 as input parameter of GregorianCalendar. Then SS probably stands for minutes, not seconds?! Look at this commented code:

// don't use the Calendar class, you surely want the gregorian calendar
GregorianCalendar calendar = new GregorianCalendar(2014, 02, 20, 9, 30, 00); // not 14!!!

// getting time zone via zone name PST which is not unique, it could also stand for 
// Pakistan Standard Time, try to use "America/Los_Angeles" (more reliable)
TimeZone tz = TimeZone.getTimeZone("PST");
calendar.setTimeZone(tz);

// output of java.util.Date#toString() depends on local time zone (my case Europe/Berlin => CET)
System.out.println(calendar.getTime()); // Tue Mar 20 18:30:00 CET 14

// PST is 8 hours behind UTC and 9 hours behind CET
System.out.println("PST: " + tz.getRawOffset() / 3600000);

// correct output in PST-zone with your wish format
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(tz);
System.out.println(sdf.format(calendar.getTime()));

I get as output: Thu Mar 20 09:30:00 PDT 2014

So PDT instead of PST (daylight saving activated at this time point in PST-zone.

System.out.println(tz.inDaylightTime(calendar.getTime())); // true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top