【问题标题】:Date formatting according to country habbits根据国家习惯格式化日期
【发布时间】:2012-04-25 22:57:47
【问题描述】:

我们创建的 J2SE 应用程序必须根据用户来自的国家/地区的自定义设置日期和时间的格式。我想问如何在Java中解决这个问题?可能我会使用 SimpleDateFormat,但我想知道是否有可能以某种更简单的方式获取格式字符串,而不是分别为每个国家/地区提供所有格式字符串。

【问题讨论】:

  • 如果您必须为每个国家/地区以相同的格式显示日期,您可以使用 DateFormat With locale。 DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());

标签: java date time format simpledateformat


【解决方案1】:

DateFormat已经允许您这样做 - 只需使用 DateTimeFormat.getDateTimeInstance(dateStyle, timeStyle, locale) 或类似的东西,具体取决于您的需要。

【讨论】:

  • 是的,我试过了,这就是我的问题的解决方案,谢谢!
【解决方案2】:

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

使用现代日期时间 API java.time 的解决方案:

使用 DateTimeFormatter.#ofLocalizedDate 获取 ISO 年表的特定于区域设置的日期格式。

演示:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfDateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
                .localizedBy(new Locale("cs", "CZ"));
        DateTimeFormatter dtfDateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                .localizedBy(new Locale("cs", "CZ"));
        DateTimeFormatter dtfDateShort = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
                .localizedBy(new Locale("cs", "CZ"));

        LocalDate date = LocalDate.now(ZoneId.of("Europe/Prague"));

        System.out.println(date.format(dtfDateFull));
        System.out.println(date.format(dtfDateMedium));
        System.out.println(date.format(dtfDateShort));
    }
}

样本运行的输出:

neděle 18. července 2021
18. 7. 2021
18.07.21

ONLINE DEMO

Trail: Date Time 了解有关现代日期时间 API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2013-11-02
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多