簡體   English   中英

在 API 級別 21 上將日期的時區更改為 UTC

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

我有一個日期,我需要將此日期的時區更改為 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM