Java convert UTC timestamp to local DateTime

2019-01-28 04:50发布

问题:

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.

回答1:

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 "";
    }


回答2:

You can try this

 String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss a z" ;
 final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
 String dateTimeString =  sdf.format(new Date());
 System.out.println(dateTimeString);   // current UTC time
 long timeStamp=sdf.parse(dateTimeString).getTime(); //current UTC time in milisec
 Calendar cal = Calendar.getInstance();
 cal.setTime(new Date(timeStamp));
 cal.add(Calendar.HOUR_OF_DAY, 5);
 cal.add(Calendar.MINUTE, 30);
 System.out.println(sdf.format(cal.getTime()));  // time relevant to UTC+5.30


回答3:

U can use Joda time to convert local to UTC and vice-versa e.g Local to UTC


DateTime dateTimeNew = new DateTime(date.getTime(), DateTimeZone.forID("Asia/Calcutta"));
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss");
    long milis = 0;
    try {
        milis = simpleDateFormat.parse(datetimeString).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }