如何从系统/上下文/区域设置提供的DateFormat中剥离年份

问题描述

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

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

  • 同一天:仅以用户区域设置格式显示时间
  • 同一年:剥离显示的年份,但显示其余部分(日期,月份和时间)
  • 其他:在用户区域设置中显示整个日期

我还希望将月份写为1月或2月,而不是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)的语言环境:

如果两种语言都在同一天发生,我想显示没有日期的时间:

德国:

  • 11:33

状态

  • 上午11:33(如果手机处于12h模式)
  • 11:33(如果手机处于24h模式)

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

德国:

  • 29 Aug 11:33

状态:

  • 8月29日11:33

这里发生了什么?德国的常规模式为dd MMM yyyy,而州的常规模式为yyyy MMM dd。因为如果是同一年,则不需要这一年。我希望删除该年。

不同年份:

德国:

  • 19年8月30日11:33

状态

  • 19 Aug 30 11:33

(实际上,我不确定我是否为各州使用了正确的datetimepattern,但是我想您可以明白这一点。我想保留所有与区域设置特定的Date / DateTime模式。但是删除日期。

即使我用StringManipulating它,也将其中所有的“ y”都删除

解决方法

另一个更新:

您可以通过以下方式从模式中删除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,"y. M. d. a h:mm","d MMM y 'г'.,"dd MMM y,"y/MM/dd H:mm","d. MMM y,"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

您还可以检查this以获得更多解释和正则表达式演示。

正则表达式的解释:

  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,locale);
        // Build a pattern for date and time
        String dateTimePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,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,locale);
        String timePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null,locale);
        String dateTimePatternGermany = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,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,locale);
        String timePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(null,locale);
        String dateTimePatternUS = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.MEDIUM,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,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
,

由于您希望能够不使用年份进行格式化/解析,因此您无法使用内置的本地化格式,因此必须构建自己的格式模式。

由于某些部分是可选的,因此您需要3种模式(完整,无年份和无日期)。通过定义可选部分并使用parseDefaulting()提供可选值,可以将完整模式重新用于解析。

首先,这是一个地图,用于为某些语言环境定义一些日期/时间格式模式,以及用于获取特定模式的辅助方法:

input_width: 2 Years => 365 * 2 = 730
label_width: Entire Feb Month => 28
shift: We are not predicting from Jan 1st 2017 but are shifting by entire Month of Jan => 30
train_df,test_df,val_df => Self Explanatory
label_columns : Name of the Target Column

private static final Map<Locale,List<String>> FORMATS = Map.of( Locale.ENGLISH,List.of("[MMM d[,uuuu],]h:mm a","MMM d,"h:mm a"),Locale.FRENCH,List.of("[d MMM[ uuuu] ]HH:mm","d MMM HH:mm","HH:mm" ),Locale.GERMAN,List.of("[dd.MM[.uuuu],]HH:mm","dd.MM,Locale.JAPANESE,List.of("[[uuuu/]MM/dd ]H:mm","MM/dd H:mm","H:mm" ) ); private static String getFormat(Locale locale,int index) { List<String> formats = FORMATS.get(locale); if (formats == null) throw new IllegalArgumentException("Format patterns not available for locale " + locale.toLanguageTag()); return formats.get(index); } Map.of()都是在Java 9中添加的,为方便起见在这里使用。

要格式化List.of(),请使用以下方法:

LocalDateTime

要将格式化的字符串解析回static String format(LocalDateTime dateTime,Locale locale) { LocalDate today = LocalDate.now(); if (dateTime.toLocalDate().equals(today)) return dateTime.format(DateTimeFormatter.ofPattern(getFormat(locale,2),locale)); if (dateTime.getYear() == today.getYear()) return dateTime.format(DateTimeFormatter.ofPattern(getFormat(locale,1),locale)); return dateTime.format(DateTimeFormatter.ofPattern(getFormat(locale,0),locale)); } ,请使用此方法,该方法使用LocalDateTime提供今天的日期作为默认值:

parseDefaulting()

测试

static LocalDateTime parse(String dateTime,Locale locale) {
    LocalDate today = LocalDate.now();
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern(getFormat(locale,0))
            .parseDefaulting(ChronoField.YEAR,today.getYear())
            .parseDefaulting(ChronoField.MONTH_OF_YEAR,today.getMonthValue())
            .parseDefaulting(ChronoField.DAY_OF_MONTH,today.getDayOfMonth())
            .toFormatter(locale);
    return LocalDateTime.parse(dateTime,formatter);
}

流仅用作对输出进行排序的便捷方式。

输出

public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    FORMATS.keySet().stream().sorted(Comparator.comparing(Locale::getDisplayLanguage)).forEachOrdered(locale -> {
        System.out.println(locale.getDisplayLanguage() + ":");
        test(now.minusYears(1),locale);
        test(now.minusDays(1),locale);
        test(now,locale);
    });
}

private static void test(LocalDateTime dateTime,Locale locale) {
    String formatted = format(dateTime,locale);
    LocalDateTime parsed = parse(formatted,locale);
    System.out.printf("  %s  formats to  %-23s and parses back to  %s%n",dateTime,formatted,parsed);
}