i need to store createdOn (One Of the Attribute in Domain Class) . i am getting the system time and storing the value for this attribute.. My Time zone is (GMT+5:30 Chennai, Kolkata,Mumbai, New Delhi ) when i upload to the server it stores UTC time . I want it to be IST (Indian Standard Time) My Application Uses Groovy on Grails. Please Help me to adjust UTC /IST Time Difference. Thanks In advance
No, don't do that. Ever!
If you store times in local form, you're in for a world of pain. You basically have to store both the local time and the local timezone and the display of the time then becomes a complex beast (working out the source and target timezones).
All times should be stored as UTC. No exception. Times entered by a user should be converted to UTC before being written anywhere (as soon as possible).
Times to be shown to a user should be converted from UTC to local as late as possible.
Take this advice from someone who once got bogged down in the multi-timezone quagmire. Using UTC and converting only when necessary will make your life a lot easier.
Once you have the UTC time, it's a matter of using the SimpleDateFormat
class to convert it:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class scratch {
public static void main (String args[]) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone (TimeZone.getTimeZone ("IST"));
System.out.println ("Time in IST is " + sdf.format (now));
}
}
This outputs:
Time in IST is 2011-04-11 13:40:04
which concurs with the current time in Mirzapur, which I think is where IST is based (not that it matters in India at the moment since it only has one timezone).
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sf.format(new Date()));
SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sf1.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println(sf1.format(new Date()));
System.out.println(Arrays.asList(TimeZone.getDefault()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With