【问题标题】:Calendar.getTime() to Date objectCalendar.getTime() 到 Date 对象
【发布时间】:2016-10-12 07:39:08
【问题描述】:

我有一个使用 UTC 时区设置的日历实例,我需要使用 UTC,因为我必须与 UTC 的服务器同步。

我需要从这个日历创建一个日期对象,我使用 Calendar.getTime()。

但是当我尝试打印出 Date 对象时,我看到它具有不同的时区(CEST 而不是 UTC)

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(timeMillisecond);
Date d = cal.getTime();
Log.d("TAG", d.toString());

编辑:

当我将日期对象传递给服务器时,我使用 CEST 时区而不是 UTC 时区来获取它。

【问题讨论】:

  • Date 对象没有时区。它只代表一个瞬间。 Date.toString() 在系统本地时区显示该时刻。
  • 我已经编辑了问题。
  • 不幸的是,这不是一种有用的方式。我们不知道您如何将日期传递给服务器,但我们可以看到您记录调用 Date.toString() 的结果 - 请参阅我之前的评论。请注意,您使用 Calendar 的代码并没有做任何有用的事情 - 您实际上得到了 Date d = new Date(timeMillisecond);
  • 我使用改造将其发送到 django rest 框架
  • 我对这两件事一无所知,但从根本上说,如果你在 Date 对象上调用 toString() 并且这是你与服务器通信的一部分,那么你做错了.

标签: java android django date calendar


【解决方案1】:

您可以使用 sdf,设置其时区并进行相应的解析。

SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

try {
                            Date dt = sdf.parse(sdf.format(Calendar.getInstance()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

这对我有用。

【讨论】:

    【解决方案2】:

    试试下面的代码,它将为您提供 UTC 日期。

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy dd,MM hh:mm:ss", Locale.getDefault());
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String utcTime = dateFormat.format(new Date(timeMillisecond));
    Log.d("TAG", utcTime);
    

    它将以 yyyy dd,MM hh:mm:ss 格式为您提供日期,但您可以根据需要提供其他格式。

    【讨论】:

    • 你几乎肯定不想使用hh,除非你还包括一个 am/pm 说明符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多