UTC T0 time conversion Local time in Java or Groovy

I need to save createdOn (one of the attributes in the domain class). I get the system time and save the value for this attribute. My time zone (GMT + 5: 30 Chennai, Calcutta, Mumbai, New Delhi), when I boot to the server, it stores UTC time. I want this to be IST (Indian Standard Time). My application uses Groovy for Grails. Please help me configure the UTC / IST Time Difference. thanks in advance

+4
source share
2 answers

No, do not do this. Someday!

If you keep time in local form, you are in a world of pain. Basically, you should store both local time and the local time zone, and displaying the time becomes a complex animal (developing source and target time zones).

All time should be stored as UTC. No exceptions. The time entered by the user must be converted to UTC before being recorded anywhere (as soon as possible).

The time that should be displayed to the user must be converted from UTC to local as late as possible.

Take this advice from those who once got bogged down in a bog. Using UTC and converting only when necessary will greatly facilitate your life.


Once you have UTC time, you need to use 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)); } } 

It is output:

 Time in IST is 2011-04-11 13:40:04 

which is consistent with the current time in Mirzapur , which, in my opinion, is based on IST (not so important in India at the moment it has only one time zone).

+22
source
  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())); 
+3
source

Source: https://habr.com/ru/post/1347501/


All Articles