2

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

4

2 回答 2

2

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

于 2012-04-13T15:00:39.823 回答
1

java.time

java.util日期时间 API 及其格式化 API已SimpleDateFormat过时且容易出错。建议完全停止使用它们并切换到现代 Date-Time API *

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

用于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 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

于 2021-07-18T16:38:51.190 回答