Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert UTC timestamp to local DateTime

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.

like image 776
kazemipouya Avatar asked Sep 09 '13 04:09

kazemipouya


1 Answers

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 "";
    }
like image 102
Biraj Zalavadia Avatar answered Sep 22 '22 19:09

Biraj Zalavadia