【问题标题】:Changing timezone of the date to UTC on API Level 21在 API 级别 21 上将日期的时区更改为 UTC
【发布时间】:2020-02-27 12:19:18
【问题描述】:

我有一个日期,我需要将此日期的时区更改为 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 上的问题?

【问题讨论】:

  • A java.util.Date 没有时区,它只是自 1970 年 1 月 1 日 00:00 UTC 以来大约毫秒的一个薄包装。时区仅在解析或打印时才相关。

标签: java android datetime


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 时区不变
    【解决方案3】:

    不使用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2017-09-15
      • 2015-06-14
      • 2017-08-12
      • 2019-09-07
      • 1970-01-01
      相关资源
      最近更新 更多