首页 > 解决方案 > 如何从系统/上下文/语言环境提供的 DateFormat 中删除年份

问题描述

我想获取LocalDateTime特定日期的字符串表示形式。目前提供的日期仍然是一个旧java.util.Date对象。但该方法应使用现代LocalDateAPI。

我想要实现的是用户当前语言环境中给定日期的简短表示。我有三个案例:

如果这仍然与用户区域设置一致,我还希望将月份写为 Jan 或 Feb 而不是 01 或 02。

我的问题是:如何从特定于上下文的 DateFormat 中删除年份,以及如何获取月份不是 01 而是 Jan 的语言环境日期字符串。

这就是我现在所拥有的:

public static String getLocaleDateTimeStringShort(Context context, Date date) {
        if (date != null && context != null) {
            //TODO: Display Jan instead 01
            LocalDateTime ld = date.toInstant().atZone(ZoneOffset.UTC).toLocalDateTime();
            LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
            DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
            DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context);
            if(ld.getDayOfMonth()==now.getDayOfMonth() && ld.getMonthValue()==now.getMonthValue() && ld.getYear()==now.getYear()) {
                //Same day
                return timeFormat.format(date);
            } else if(ld.getYear()==now.getYear()){
                //Same year
                /* TODO: Strip year from date */
                //dateFormat.
            }else{
                return dateFormat.format(date) + " " + timeFormat.format(date);
            }
        }
        return null;
    }

更新

我注意到对于我想要实现的目标可能会感到困惑。让我们看一些例子:

使用德国 (dd MMM yy HH:mm) 和美国 (yy MMM dd HH:mm) 的语言环境:

如果两个语言环境在同一天发生了什么事,我想显示没有日期的时间:

德国:

状态

现在,第二种情况将是同一年内的日期:

德国:

状态:

这里发生了什么?德国的正常模式是 dd MMM yyyy 和州 yyyy MMM dd。因为如果与我们所在的年份相同,则不需要该年份。我希望将年份剥离。

不同年份:

德国:

状态

(我实际上不确定我是否为各州使用了正确的 datetimepattern,但我认为您可以看到这一点。我想保留特定于语言环境的 Date/DateTime Pattern 的所有内容。但去掉日期。

我即使 StringManipulating 它并从中删除所有“y”

标签: androidlocalizationlocaldatejava.util.date

解决方案


另一个更新:

year您可以通过以下方式从图案中移除零件:

public class Main {
    public static void main(String[] args) {
        // Test patterns
        String[] patterns = { "MMM d, y, h:mm a", "d MMM y, HH:mm", "y年M月d日 ah:mm", "dd.MM.y, HH:mm", "y. M. d. a h:mm",
                "d MMM y 'г'., HH:mm", "dd MMM y, HH:mm", "y/MM/dd H:mm", "d. MMM y, HH:mm", "dd‏/MM‏/y h:mm a",
                "dd.M.y HH:mm", "d MMM y HH:mm" };
        for (String pattern : patterns) {
            System.out.println(pattern.replaceAll("([\\s,.\\/]\\s*)?y+[.\\/]?", "").trim());
        }
    }
}

输出:

MMM d, h:mm a
d MMM, HH:mm
年M月d日 ah:mm
dd.MM, HH:mm
M. d. a h:mm
d MMM 'г'., HH:mm
dd MMM, HH:mm
MM/dd H:mm
d. MMM, HH:mm
dd‏/MM‏ h:mm a
dd.M HH:mm
d MMM HH:mm

您还可以查看这个以获得更多解释和正则表达式的演示。

正则表达式的解释:

  1. ([\s,.\/]\s*)?指定由空格、逗号、点或正斜杠组成的可选组,后跟任意数量的空格
  2. y+指定一个或多个y
  3. [.\/]?在后面指定一个可选的点或正斜杠y+

更新:

在原始答案中,日期时间部分固定在模式中的特定位置。我编写了此更新,因为 OP 已请求帮助以显示日期时间部分的特定于区域设置的位置。

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // A sample java.util.Date instance
        Date date = new Date();

        // Convert Date into LocalDateTime at UTC
        LocalDateTime ldt = date.toInstant().atZone(ZoneOffset.UTC).toLocalDateTime();

        // Instantiate Locale with the default locale
        Locale locale = Locale.getDefault();

        // Build a pattern for date
        String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM, null,
                IsoChronology.INSTANCE, locale);
        // Build a pattern for time
        String timePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, FormatStyle.MEDIUM,
                IsoChronology.INSTANCE, locale);
        // Build a pattern for date and time
        String dateTimePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
                FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);

        System.out.println("Test reslts for my default locale:");
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePattern, locale)));
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(timePattern, locale)));
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(dateTimePattern, locale)));

        // Let's test it for the Locale.GERMANY
        locale = Locale.GERMANY;
        System.out.println("\nTest reslts for Locale.GERMANY:");
        String datePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM, null,
                IsoChronology.INSTANCE, locale);
        String timePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, FormatStyle.MEDIUM,
                IsoChronology.INSTANCE, locale);
        String dateTimePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
                FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePatternGermany, locale)));
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(timePatternGermany, locale)));
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(dateTimePatternGermany, locale)));

        // Let's test it for the Locale.US
        locale = Locale.US;
        System.out.println("\nTest reslts for Locale.US:");
        String datePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM, null,
                IsoChronology.INSTANCE, locale);
        String timePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null, FormatStyle.MEDIUM,
                IsoChronology.INSTANCE, locale);
        String dateTimePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,
                FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePatternUS, locale)));
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(timePatternUS, locale)));
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(dateTimePatternUS, locale)));
    }
}

输出:

Test reslts for my default locale:
30 Aug 2020
09:24:04
30 Aug 2020, 09:24:04

Test reslts for Locale.GERMANY:
30.08.2020
09:24:04
30.08.2020, 09:24:04

Test reslts for Locale.US:
Aug 30, 2020
9:24:04 AM
Aug 30, 2020, 9:24:04 AM

原答案:

根据您的问题,以下代码具有您需要的所有内容:

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // A sample java.util.Date instance
        Date date = new Date();

        // Convert Date into LocalDateTime at UTC
        LocalDateTime ldt = date.toInstant().atZone(ZoneOffset.UTC).toLocalDateTime();

        // Get the string representing just time part
        String sameDayDateTime = ldt.format(DateTimeFormatter.ofPattern("HH:mm:ss", Locale.getDefault()));
        System.out.println(sameDayDateTime);

        // Get the string representing all parts except year
        String sameYearDateTime = ldt.format(DateTimeFormatter.ofPattern("MMM dd, HH:mm:ss", Locale.getDefault()));
        System.out.println(sameYearDateTime);

        // Display the default string representation of the date-time
        String defaultDateTimeStr = ldt.toString();
        System.out.println(defaultDateTimeStr);

        // Display the string representation of the date-time in custom format
        String customDateTimeStr = ldt
                .format(DateTimeFormatter.ofPattern("yyyy MMM dd, HH:mm:ss", Locale.getDefault()));
        System.out.println(customDateTimeStr);
    }
}

输出:

21:37:24
Aug 28, 21:37:24
2020-08-28T21:37:24.697
2020 Aug 28, 21:37:24

推荐阅读