【问题标题】:Android java get current time in 24 hours formatAndroid java获取24小时格式的当前时间
【发布时间】:2018-08-30 07:12:15
【问题描述】:

我正在尝试使用以下代码以 24 小时格式获取当前时间:

Calendar cal = Calendar.getInstance();
int currentHour = cal.get(Calendar.HOUR);
int currentMinute = cal.get(Calendar.MINUTE);

System.out.println(currentHour);
System.out.println(currentMinute);

我现在的时间是新加坡时间下午 3.11 点。但是当我执行上面的代码时,我得到了 7.09。有什么想法吗?

【问题讨论】:

  • 使用 HOUR_OF_DAY 插入 HOUR
  • @AntonA。鉴于至少分钟实际匹配,仍然与输出不匹配
  • @XtremeBaumer 你确定你的手机时间不等于输出吗?
  • @AntonA。我不是OP。但是看看给定的时间,他的代码实际上应该输出3:11 而不是7:097:11
  • @ADM 不重复。我也试过了,但是小时是错误的,只是分钟是正确的

标签: java android time calendar


【解决方案1】:

我已经想到了解决方案:

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
currentHour = cal.get(Calendar.HOUR_OF_DAY);
currentMinute = cal.get(Calendar.MINUTE);

上面的代码完全符合我的要求

【讨论】:

  • 我推荐Asia/Singapore 而不是GMT+8
  • 我没有给出任何时区。但有确切的时间
【解决方案2】:

这将为您提供 24 小时格式的时间

public String getFormattedTime() {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    return dateFormatter.format(calendar.getTime());
}

【讨论】:

  • 但是返回的小时是错误的,虽然分钟是正确的
  • 试试这个方法。希望它有效 "String formattedDate = dateFormat.format(new Date()).toString();"
  • 请不要教年轻人将早已过时且臭名昭著的SimpleDateFormat课程作为首选或毫无保留地使用。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中有很多更好的东西。是的,您可以在 Android 上使用它。对于较旧的 Android,请参阅 How to use ThreeTenABP in Android Project。你的代码也不能解决提问者的问题。
【解决方案3】:

从您提供的信息中我无法确定,但可能的原因是您的 JVM 的时区设置是 UTC。如果您在新加坡时间 15:09:55 运行程序,则在 UTC 中将打印为 7 和 9。如果您在一分钟后读取新加坡时间的时钟,或者从与您的设备(或模拟器)不完全同步的时钟读取它,它将显示下午 3:11。

JVM 通常会从设备中获取其时区设置,但可能有各种原因导致它从其他地方获取它。

正如 Anton A. 在评论中所说,对于 24 小时格式,您需要 HOUR_OF_DAY 而不是 HOUR(尽管 UTC 时间是上午 7:09,所以这个错误不是意外小时的原因在你的情况下)。

java.time

打印当前时间的现代方式是:

    System.out.println(LocalTime.now(ZoneId.of("Asia/Singapore")));

您使用的Calendar 类早已过时且设计不佳。 LocalTime 是来自 java.time 的类,现代 Java 日期和时间 API,它表示一天中的时间(没有时区,但 now 方法接受时区以初始化为该区域的当前时间) .如果您的 Android 设备不是新设备(在 API 级别 26 下),您需要the ThreeTenABP library 才能使用它。见How to use ThreeTenABP in Android Project

另一个链接:Oracle tutorial: Date Time 解释如何使用java.time

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多