Convert UTC Time T0 Local Time In Java or Groovy

后端 未结 2 1721
野趣味
野趣味 2021-01-05 17:49

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,

相关标签:
2条回答
  • 2021-01-05 18:06
            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()));
    
    0 讨论(0)
  • 2021-01-05 18:07

    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).

    0 讨论(0)
提交回复
热议问题