根据国家习惯格式化日期

时间:2012-04-13 14:55:43

标签: java date time format simpledateformat

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern 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 了解有关现代 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

相关问题