简体   繁体   English

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

[英]Changing timezone of the date to UTC on API Level 21

I have a Date and I need to change timezone of this date to UTC.我有一个日期,我需要将此日期的时区更改为 UTC。 The code below does not work.下面的代码不起作用。

    Calendar cal = Calendar.getInstance();

    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(dateLocal.getTime());

    return new Date(cal.getTimeInMillis());

On the Stackoverflow all examples return either a String or use API 26. How can I solve my problem on the Android API 21?在 Stackoverflow 上,所有示例都返回字符串或使用 API 26。如何解决我在 Android API 21 上的问题?

Try this:尝试这个:

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

Use cal.getTime();使用cal.getTime(); which returns date返回日期

The same result you can get without SimpleDateFormat:不使用 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM