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

如何解决如何从系统/上下文/区域设置提供的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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-