Java日期时间格式检查和重置 [英] Java date time format check and reset

查看:240
本文介绍了Java日期时间格式检查和重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String是一个输入,我必须检查它是否是这些格式中的任何一种。如果它是sdf1格式然后传递,如果它在sdf2,3 ....然后我添加缺少格式并用sdf1格式解析它

String is an input and i have to check whether it is in any of these formats. If it is in sdf1 format then pass, if it is in sdf2,3.... then i add the missing the format and parse it with sdf1 format

SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa");
SimpleDateFormat sdf3 = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
SimpleDateFormat sdf3 = new SimpleDateFormat("MM/dd/yyyy hh:mma");
SimpleDateFormat sdf3 = new SimpleDateFormat("MM/dd/yyyy hh:mm");
SimpleDateFormat sdf3 = new SimpleDateFormat("MM/dd/yyyy"); 

这是我所拥有的

try{
            // Parse if it is MM/dd/yyyy hh:mm:ss a
            cal = Calendar.getInstance();
            cal.setTime(sdf1.parse(inStr));
          }catch(Exception exp){
             try{
               cal = Calendar.getInstance();
               //Parse if it is MM/dd/yyyy hh:mm:ssa                      
               sdf2.parse(inStr);                 
               inStr = new StringBuilder(inStr).insert(str.length()-2, " ").toString();
               cal.setTime(sdf1.parse(inStr));
              }catch(Exception dte2){
                try{
                    cal = Calendar.getInstance();
                    //Parse if it is MM/dd/yyyy hh:mma
                    sdf3.parse(inStr);
                    //if pass then set 00:00:00 AM
                    inStr = inStr+" AM";
                    inStr = new StringBuilder(inStr).insert(str.length()-2, ":00").toString();
                    cal.setTime(sdf1.parse(inStr));

它继续像尝试解析一样,如果在异常块检查中失败则检查下一个。
有没有简单的方法可以做到这一点,可能在JAVA 8中?
i可以使用标记为重复的链接来讨论如何解析,但我有额外的要求,因为缺少格式的自动完成。

it keeps going like try parsing and if failed in exception block check for the next one. Is there any easy way to do this, may be in JAVA 8? i could use the link from marked as duplicate it talks about how to parse, but i have additional requirement as auto complete with missing format.

推荐答案

在Java 8中,您可以使用 java.time.format.DateTimeFormatter ,包含许多可选部分 - 由 [] :

In Java 8, you can use a java.time.format.DateTimeFormatter with lots of optional sections - delimited by []:

DateTimeFormatter fmt = DateTimeFormatter
    .ofPattern("MM/dd/yyyy[ hh:mm[[:ss][ ]a]][HH:mm]", Locale.US);

如果您只想验证输入 - 并且不将结果分配给日期/时间变量 - 只需调用解析即可。这适用于以下所有情况:

If you want just to validate the inputs - and don't assign the result to a date/time variable - just calling parse is enough. This works for all the cases below:

fmt.parse("10/20/2018");
fmt.parse("10/20/2018 10:20");
fmt.parse("10/20/2018 10:20AM");
fmt.parse("10/20/2018 10:20 AM");
fmt.parse("10/20/2018 10:20:30AM");
fmt.parse("10/20/2018 10:20:30 AM");

如果输入无效,它将抛出 DateTimeParseException

If the input is invalid, it'll throw a DateTimeParseException.

请注意 HH hh H 适用于小时(0到23之间的值),而 h 适用于上午时钟小时(1到12之间的值)。 H 不能与AM / PM指示符一起使用,而 h 必须有AM / PM才能消除它的歧义。这就是为什么有2个不同的可选部分,每个部分都有一个。

Note that there's a difference between HH and hh. H is for hour-of-day (values between 0 and 23), while h is for clock-hour-of-am-pm (values between 1 and 12). H can't be with AM/PM designator, while h must have AM/PM to disambiguate it. That's why there are 2 different optional sections, one with each field.

我还使用 Locale.US 因为AM / PM字符串已本地化。虽然对于大多数语言环境,结果是AM或PM,对于其他一些语言环境,它可以是小写(am),或其他一些值(午后,日语,例如)。

I also use Locale.US because AM/PM strings are localized. Although for most locales, the result is "AM" or "PM", for some others it can be lowercase ("am"), or some other values (午後 in Japanese, for example).

如果未设置区域设置,则使用JVM默认值。但我更喜欢将它设置为特定的一个,我知道它可以使用我的输入。

If you don't set the locale, it uses the JVM default. But I prefer to set it a specific one that I know it'll work with the inputs I have.

打印那些价值再次,在所有领域,这有点棘手。
输入只能有一个日期(日,月,年),或日期和时间(日,月,年,小时,分钟),所以一种方法是使用 LocalDateTime (并在不存在时设置缺少的字段)。

To print those values again, with all the fields, it's a little bit tricky. The inputs can have only a date (day, month, year), or a date and time (day, month, year, hour, minute), so one alternative is to use a LocalDateTime (and set the missing fields when not present).

您可以使用 parseBest 然后检查已解析的类型:

You can use parseBest and then check the type that was parsed:

// parse, try to create a LocalDateTime - if it's not possible, try a LocalDate
TemporalAccessor parsed = fmt.parseBest("10/20/2018", LocalDateTime::from, LocalDate::from);
LocalDateTime dt = null;
if (parsed instanceof LocalDateTime) {
    // LocalDateTime parsed (all fields set)
    dt = (LocalDateTime) parsed;
} else if (parsed instanceof LocalDate) {
    // LocalDate parsed (set time fields)
    dt = ((LocalDate) parsed)
        // set time (use whatever value you want - I'm using 10 AM as example)
        .atTime(LocalTime.of(10, 0));
}

然后你使用另一个格式化程序输出 - 这是因为第一个格式化程序将打印全部格式化时的可选部分,因此它会打印两次小时。只需创建另一个,就是这样:

Then you use another formatter for output - that's because the first formatter will print all the optional sections when formatting, so it'll print the hours twice. Just create another one and that's it:

DateTimeFormatter outputFmt = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a", Locale.US);
System.out.println(dt.format(outputFmt)); // 10/20/2018 10:00:00 AM

这篇关于Java日期时间格式检查和重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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