在API 21级上将日期的时区更改为UTC



我有一个日期,我需要将该日期的时区更改为UTC。下面的代码不起作用。

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(dateLocal.getTime());
return new Date(cal.getTimeInMillis());

在Stackoverflow上,所有示例都返回字符串或使用API 26。如何在Android API 21上解决我的问题?

试试这个:

public Date getDateInUtc() {
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
Date dateToReturn = null;
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
String utcTime = sdf.format(new Date());
try {
dateToReturn = dateFormat.parse(utcTime);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}

使用返回日期的cal.getTime();

没有SimpleDateFormat:也能得到相同的结果

public Date dateInUtc(Date input) {
Calendar inputCalendar = Calendar.getInstance();
inputCalendar.setTime(input);
TimeZone timeZone = inputCalendar.getTimeZone();
long timeInUtc = input.getTime() - timeZone.getRawOffset();
Calendar outputCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
outputCalendar.setTimeInMillis(timeInUtc);
return outputCalendar.getTime();
}

最新更新