【问题标题】:How to get current timestamp with TimeZone in Java如何在 Java 中使用 TimeZone 获取当前时间戳
【发布时间】:2019-07-21 19:16:29
【问题描述】:

我想获得timeStamp 并考虑在Android 中使用Java 中的TimeZone, 我尝试了很多方法,但仍然找不到解决方案。

【问题讨论】:

  • 获取ThreeTenABP 库并使用ZonedDateTime 类。如果不是这样,请编辑问题并详细说明“考虑时区”的含义

标签: java android time timestamp


【解决方案1】:

您可以使用此方法获取带有时区的时间戳:

public static long getTimestampWithGMT() {
    long timestamp = System.currentTimeMillis() / 1000;
    int offset = (TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings()) / 1000;

    return timestamp + offset;
}

【讨论】:

    【解决方案2】:

    tl;博士

    使用 java.time 包中的 ZoneIdZonedDateTime 类。

    ZonedDateTime.now()  // Implicitly applies the JVM’s current default time zone.
    

    最好明确指定您想要/预期的时区。

    ZonedDateTime.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
    

    java.time

    现代方法使用 java.time 类,这些类在几年前取代了可怕的遗留类,例如 TimestampCalendarDateTimeZoneSimpleDateFormat

    Continent/Region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 2-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

    ZoneId z = ZoneId.of( "America/Montreal" ) ;  
    

    通过特定地区(上述时区)的人们使用的挂钟时间捕捉当前时刻。

    ZonedDateTime zdt = ZonedDateTime.now( z ) ;
    


    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

    您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

    从哪里获得 java.time 类?

    【讨论】:

      【解决方案3】:

      你可以使用 Calendar.getInstance().getTimeInMillis() 吗?它默认为设备时区,或者如果您想更改时区,您可以执行以下操作

      Calendar calendar = Calendar.getInstance();
      calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
      calendar.getTimeInMillis();
      
      

      【讨论】:

      • getTimeInMillis() "将当前时间返回为距纪元的 UTC 毫秒数"(引用 javadoc),因此设置时区无效,您也可以只需致电System.currentTimeMillis()
      【解决方案4】:

      您可以使用 Calendar 类来获取当前时间戳。然后您可以格式化此时间戳以显示日期、日期、月份、年份、时间等。

      Calendar c = Calendar.getInstance(); 
      

      查看此链接: Calendar class in java with examples (GeeksForGeeks)

      【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2012-01-10
      • 2011-02-16
      • 2017-02-15
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2021-02-07
      • 2018-04-09
      相关资源
      最近更新 更多