【问题标题】:How to get perfect UTC Time in java/android?如何在 java/android 中获得完美的 UTC 时间?
【发布时间】:2021-10-02 23:09:24
【问题描述】:

我正在尝试在我的应用程序中获取 UTC 时间,但不幸的是,每次我获取当前模拟器的日期和时间而不是 UTC。

试过了,

  1. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

  2. ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);

  3. DateTime now = DateTime.now(DateTimeZone.UTC);

我的代码:

//create UTC time
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    System.out.println("DATETIME ==> " + cal.getTime());
    ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
    System.out.println("DATETIME = " + utcTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    DateTime now = DateTime.now(DateTimeZone.UTC);
    System.out.println("DATETIME = " + now);

非常感谢任何帮助。

【问题讨论】:

  • 当我将模拟器时间设置为网络提供的时间时,它工作正常。那么,为什么会发生这种情况,你能解释一下吗??
  • UTC 取决于设备时间?
  • 好的,我明白了..谢谢
  • 这能回答你的问题吗? How to get current time from internet in android

标签: java android android-studio datetime


【解决方案1】:

试试这个代码:

private String getCurrentDateTimeAccordingToUTC(String format) {
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return simpleDateFormat.format(date);
}


String date = getCurrentDateTimeAccordingToUTC("dd-MM-yyyy hh:mm:ss a");
Log.e("date--","inUTC--:"+date);

【讨论】:

  • 得到这个 UTC 时间:==> 2021-07-26T15:05 但实际上 UTC 日期是 ==> 27,我得到 26,这是我的模拟器日期。
  • 日期时间的转换取决于设备当前的日期时间。
  • 但我不想转换我想要实际 UTC 时间。
  • 检查这个项目 - github.com/instacart/truetime-android,以获得实际的 UTC 日期时间而不依赖于设备时间
  • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。 (是的,您可以在 Android 上使用它。)
猜你喜欢
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 2016-04-01
  • 2012-07-24
  • 2018-09-24
相关资源
最近更新 更多