簡體   English   中英

SimpleDateFormat模式基於語言環境,但強制使用4位數年份

[英]SimpleDateFormat pattern based on locale, but forcing a 4-digit year

我需要建立一個像dd/MM/yyyy這樣的日期格式。 它幾乎像DateFormat.SHORT ,但包含4年的數字。

我嘗試用它來實現它

new SimpleDateFormat("dd//MM/yyyy", locale).format(date);

但是對於美國語言環境,格式錯誤。

是否有一種通用的方法來格式化基於區域設置更改模式的日期?

謝謝

我會這樣做:

    StringBuffer buffer = new StringBuffer();

    Calendar date = Calendar.getInstance();
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
    FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);

    StringBuffer format = dateFormat.format(date.getTime(), buffer, yearPosition);
    format.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), String.valueOf(date.get(Calendar.YEAR)));

    System.out.println(format);

使用FieldPosition,你真的不必關心日期的格式是否包括年份為“yy”或“yyyy”,其中年份結束,甚至使用哪種分隔符。

您只需使用年份字段的開始和結束索引,並始終將其替換為4位年份值,就是這樣。

java.time

這是現代的答案。 恕我直言,這些天沒有人應該與長期過時的DateFormatSimpleDateFormat類斗爭。 他們的替代版本在2014年初的現代Java日期和時間API中出現了java.time類

我只是將這個想法應用於Happier對現代課程的回答

DateTimeFormatterBuilder.getLocalizedDateTimePattern方法為Locale生成日期和時間樣式的格式設置模式。 我們操縱生成的模式字符串以強制使用4位數年份。

LocalDate date = LocalDate.of( 2017, Month.JULY, 18 );

String formatPattern =
    DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.SHORT, 
        null, 
        IsoChronology.INSTANCE, 
        userLocale);
formatPattern = formatPattern.replaceAll("\\byy\\b", "yyyy");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern, userLocale);

String output = date.format(formatter);

示例輸出:

  • 對於Locale.US7/18/2017
  • 適用於UKFRANCEGERMANYITALY每一個: 18/07/2017

DateTimeFormatterBuilder允許我們直接獲取本地化格式模式字符串,而無需先獲取格式化程序,這在這里很方便。 getLocalizedDateTimePattern()的第一個參數是日期格式樣式。 null作為第二個參數表示我們不希望包含任何時間格式。 在我的測試中,我使用了LocalDate作為date ,但代碼也適用於其他現代日期類型( LocalDateTimeOffsetDateTimeZonedDateTime )。

我有類似的方法來做到這一點,但我需要獲取ui控制器的語言環境模式。

所以這是代碼

            // date format, always using yyyy as year display
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        SimpleDateFormat simple = (SimpleDateFormat) dateFormat;
        String pattern = simple.toPattern().replaceAll("\\byy\\b", "yyyy");
        System.out.println(pattern);

你能不能只使用java.text.DateFormat類?

DateFormat uk = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
DateFormat us = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);

Date now = new Date();
String usFormat = us.format(now);
String ukFormat = uk.format(now);

那應該做你想做的事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM