是否有主日期时间模式可用于每个类似的日期时间模式 [英] is there master date time pattern which will work for every similar date time patterns

查看:120
本文介绍了是否有主日期时间模式可用于每个类似的日期时间模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的消费者收到的时间格式为 String ,其值为 20/5 / 14_9:22:25 20/5 / 14_9:22:5 20/5 / 14_12:22:25 20/10 / 14_9:2:25 等...

My consumer received time format is String with value 20/5/14_9:22:25 or 20/5/14_9:22:5 or 20/5/14_12:22:25 or 20/10/14_9:2:25 etc...

上述所有内容与 yy / MM / dd_HH:mm:ss
,并且可能有许多个位数,包括日,月,时,分和/或秒的数字。

all the above have very diffrent date time pattern from yy/MM/dd_HH:mm:ss and there can be many posiblity's of having single digit day,month,hour,minute and/or seconds.

是否有一个主模式,我可以将其用于 DateTimeFormatter.ofPattern(format),该模式将适用于上述所有模式?

is there a masterpattern which will i can use for DateTimeFormatter.ofPattern(format) which will work for all the above pattern??

推荐答案

模式看起来相同

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/M/dd_H:mm:s");
      LocalDate parsedDate = LocalDate.parse("20/5/14_9:22:25", formatter);
      System.out.println(parsedDate);
      parsedDate = LocalDate.parse("20/5/14_9:22:5", formatter);
      System.out.println(parsedDate);
      parsedDate = LocalDate.parse("20/10/14_9:22:25", formatter);
      System.out.println(parsedDate);  

输出

2020-05-14
2020-05-14
2020-10-14

直觉上但非常实用,对于一个数字字母,例如 M H ,不是指一位,而是需要的位数。因此 M 会同时解析 5 10 (甚至是 05 )。 H 解析 9 12 ,依此类推。两个格式字母,例如 MM HH ,表示正好两位数,因此不适用于两个月的解析5或一个小时的9。这需要 05 09 。或者如文档所述:

Counter-intuitively but very practically, for numbers one pattern letter, for example M or H, does not mean one digit but rather "as many digits as it takes". So M parses both 5 and 10 (and even 05). H parses 9 and 12, etc. By contrast two pattern letters, for example MM or HH, means exactly two digits, so will not work for parsing neither a month of 5 nor an hour of 9. It would require 05 or 09. Or as the documentation puts it:


数字:如果字母数为1,则值为使用最小位数进行输出,不带填充。否则,将数字
用作输出字段的宽度,并根据需要对
值进行零填充。 …

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary. …

因此,如果您需要接受一个数字的月份或一小时的分钟,也可以使用一个模式字母 d m

So if you need to accept one-digit day of month or one-digit minute of the hour, also use one pattern letter d and m, respectively.

但是 29 的小时数错误(就像您在问题的早期版本中一样)。

But having a hour of 29 (as you had in earlier versions of the question) is wrong.

文档链接: DateTimeFormatter

这篇关于是否有主日期时间模式可用于每个类似的日期时间模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆