【问题标题】:Show a pretty timestamp with month name显示带有月份名称的漂亮时间戳
【发布时间】:2021-12-27 17:11:14
【问题描述】:

我有一个Timestamp 对象,我想展示它。

其实我用的是new Timestamp(System.currentTimeMillis()).toLocaleString(),结果是这样的:

12 月 27 日。 2021 17:54:35

但是:

  • toLocaleString() 方法已弃用
  • 它根据计算机的语言返回值,所以它可以显示:

2021 年 12 月 27 日晚上 17:54:35

这不是我想要的。在我的个人电脑里,用法语,没问题。但是,在 VPS 上就不行了。

此外,所有找到的线程都只是在谈论格式但没有月份名称,这不是我想要的。

如何以法语轻松显示时间戳?

【问题讨论】:

    标签: java timestamp


    【解决方案1】:

    tl;博士

    使用添加到旧类Timestamp 的新转换方法来转换为现代java.time 类。

    Timestamp myTimestamp = Timestamp.from( Instant.now() );  // Simulate receiving a `Timestamp` object from old code not yet updated to *java.time*. 
    System.out.println(
            myTimestamp
                    .toInstant()                              // Convert from legacy class to modern class.
                    .atZone(                                  // Adjust into a time zone.
                            ZoneId.of( "Asia/Tokyo" )
                    )                                         // Returns a `ZonedDateTime` object. 
                    .format(
                            DateTimeFormatter
                                    .ofLocalizedDateTime(
                                            FormatStyle.FULL
                                    )
                                    .withLocale(
                                            Locale.FRANCE
                                    )
                    )                                          // Returns a `String` object, generated text.
    );
    

    查看此代码run live at IdeOne.com

    狂欢节 2021 年 12 月 28 日 à 05:39:58 heure normale du Japon

    详情

    Timestamp 是可怕的遗留日期时间类之一。这些课程是几年前的supplanted by the modern java.time 课程。切勿使用 Timestamp、Date、Calendar、SimpleDateFormat 等。

    以 UTC 格式捕捉当前时刻,偏移量为零时分秒。

    Instant instant = Instant.now() ;
    

    捕捉特定时区的当前时刻。

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

    以自动本地化格式生成文本。指定语言环境以确定翻译中使用的人类语言以及缩写、大写、元素顺序等中使用的文化规范。

    Locale locale = Locale.CANADA_FRENCH ;
    DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale ) ;
    String output = zdt.format( f ) ;
    

    如果从类似于 SQL 标准类型 TIMESTAMP WITH TIME ZONE 的数据类型的数据库列接收时刻,请使用 Java 中的 OffsetDateTime 类和符合 JDBC 4.2 或更高版本的 JDBC 驱动程序。

    OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
    

    调整到您想要的时区以生成 ZonedDateTime 对象。

    ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
    

    所有这些都已经在 Stack Overflow 上处理过很多次了。搜索以了解更多信息。

    【讨论】:

    • 我应该使用Timestamp,因为我正在从数据库中获取信息。所以,我只会使用timestamp.toInstant()。此外,“ZoneOf”方法不存在
    • @Elikill58 不,不需要使用Timestamp 类。查看我的编辑。
    • 我明白了,我会检查的,谢谢!如果它已经在 SO 上处理,只需标记为重复而不是回答
    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多