Amj*_*han 3 timezone datetime android utc
我有我设备的当前时间(以 毫秒为单位)。
现在我需要将其转换为 MILLISECONDS OF UTC 时区
所以我试过这个,但它没有以毫秒为单位进行转换。
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;
}
Run Code Online (Sandbox Code Playgroud)
UTC MILLISECOND到LOCAL TIME ZONE MILLISECOND反之亦然
请给我一些建议。
对于 LOCAL 到 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;
}
Run Code Online (Sandbox Code Playgroud)
和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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢,我得到了这个解决方案