Java convert UTC timestamp to local DateTime

22,242

Try this is working with me

public  String getDateCurrentTimeZone(long timestamp) {
        try{
            Calendar calendar = Calendar.getInstance();
            TimeZone tz = TimeZone.getDefault();
            calendar.setTimeInMillis(timestamp * 1000);
            calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currenTimeZone = (Date) calendar.getTime();
            return sdf.format(currenTimeZone);
        }catch (Exception e) {
        }
        return "";
    }
Share:
22,242
kazemipouya
Author by

kazemipouya

Updated on July 09, 2022

Comments

  • kazemipouya
    kazemipouya almost 2 years

    I know there are dozens of answered posts about converting UTC Time/Date To/From local time already but non helped me to figure out what my problem is. My question is: By having UTC timestamp, how can i get local DateTime? This is what I have right now but this just convert the timestamp to DateTime format.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getDefault());         
    sdf.format(new Date(timestamp * 1000));
    

    Edited: I'm saving the UTC timestamp on the cloud so every device (Android/iOS) can query and convert to it's time zone.

  • kazemipouya
    kazemipouya over 10 years
    I just edited the post, not possible to add hours and minutes on the code manually. This must happen based on timezone of device.
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 10 years
    @kazemipouya you are wrong. It is possible to add hours as well as minutes to current time. you must learn about Java calender.
  • kazemipouya
    kazemipouya over 10 years
    Something weird happened sometime ago, without using "calendar.add". My SimpleDateFormat start to convert UTC time to local time zone (Asia/Kuala Lumpur) automatically but 1 hour less than my device time. I suspect DST but couldn't help how to solve this!
  • eocanha
    eocanha about 10 years
    kazemipouya: It's strange, because in theory getOffset() already has into account DST. Maybe Calendar isn't the best class to compute the timezone offset addition, because it's aware of timezones and DST by itself. I'm working with UTC dates and I'm adding the timezone offset by hand: long utcTimestamp = utcDate.getTime(); Date localizedDate = new Date(utcTimestamp + TimeZone.getDefault().getOffset(utcTimestamp));