我的设备有 MILLISECONDS 的当前时间。
现在我需要将其转换为 MILLISECONDS OF UTC TIME-ZONE
所以我试过了,但它不是以毫秒为单位的转换。
public static long localToUTC(long time) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.e("* UTC : " + time, " - " + sdf.format(new Date(time)));
Date date = sdf.parse(sdf.format(new Date(time)));
long timeInMilliseconds = date.getTime();
Log.e("Millis in UTC", timeInMilliseconds + "" + new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a").format(date));
return timeInMilliseconds;
} catch (Exception e) {
Log.e("Exception", "" + e.getMessage());
}
return time;
}
反之亦然,UTC MILLISECOND 到 LOCAL TIME ZONE MILLISECOND
请给我一些建议。
最佳答案
本地到 UTC 毫秒,反之亦然
本地到 UTC
public static long localToUTC(long time) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date date = new Date(time);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String strDate = dateFormat.format(date);
// System.out.println("Local Millis * " + date.getTime() + " ---UTC time " + strDate);//correct
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date utcDate = dateFormatLocal.parse(strDate);
// System.out.println("UTC Millis * " + utcDate.getTime() + " ------ " + dateFormatLocal.format(utcDate));
long utcMillis = utcDate.getTime();
return utcMillis;
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
和 UTC 到本地
public static long utcToLocal(long utcTime) {
try {
Time timeFormat = new Time();
timeFormat.set(utcTime + TimeZone.getDefault().getOffset(utcTime));
return timeFormat.toMillis(true);
} catch (Exception e) {
e.printStackTrace();
}
return utcTime;
}
谢谢,我得到了这个解决方案
关于android - 时间转换毫秒本地时间到毫秒UTC时间在android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41062341/