简体   繁体   English

在Java中进行转换时获取不同格式的日期

[英]Getting different format of date while conversion in java

A very good morning , I have just one query, below is the program which upon execution the year gets changed. 早上好,我只有一个查询,下面是执行年份会更改的程序。 Lets say the date as input is 03/20/2020 then the date upon execution, the program comes as 03/08/2021 which is totally wrong. 比方说,日期为输入是03/20/2020 ,然后在执行之日起,该计划之际, 03/08/2021这是完全错误的。 As the year is incremented and the complete date is wrong. 随着年份的增加和完整的日期是错误的。 Please advise how can i correct my program to achieve the same date. 请告知我如何更正我的计划以达到同一日期。

public class DateFormattingTest {

    private static final SimpleDateFormat outputDate = new SimpleDateFormat(
            "dd/MM/yyyy");

    public static void main(String[] args) {

         System.out.println ("03/20/2020:" + extractDate("03/20/2020") );


        DateFormattingTest test = new DateFormattingTest();
        convertDate(test, "03/20/2020");

    }

    public static Date extractDate(String dateStr) {

        String [] datePatterns = {"yyyy-MM-dd", "dd-MM-yyyy","MM/dd/yyyy" };
        Date date = null;

        try {
            date = DateUtils.parseDate(dateStr, datePatterns);
        }
        catch (Exception except) {
                except.printStackTrace();
        }
        return date;
    }


    private static void convertDate(DateFormattingTest test, String dateString) {
        java.util.Date date = test.convertStringToDate(dateString);
        System.out.println(dateString + " -> " + outputDate.format(date));
    }

    public java.util.Date convertStringToDate(String stringValue) {
        String[] formatStrings = { "dd/MM/yy", "dd-MM-yy", "dd-MMM-yyyy" };

        for (String formatString : formatStrings) {
            try {
                java.util.Date date = new SimpleDateFormat(formatString)
                        .parse(stringValue);
                return date;
            } catch (ParseException e) {

            }
        }

        return null;

    }

}

Your original String date seems to be in the format of MM/dd/yyyy , which extractDate uses, but your convertStringToDate is using the dd/MM/yyyy format. 您原始的String日期似乎采用MM/dd/yyyy的格式, extractDate使用,但是您的convertStringToDate使用的是dd/MM/yyyy格式。

SimpleDateFormat is using the pattern dd/MM/yyyy to parse the stringValue which is actually in MM/dd/yyyy , because the formatter can't determine which values represent what, it assumes and corrects for the month been 20 , but rolling the year. SimpleDateFormat使用模式dd/MM/yyyy来解析实际在MM/dd/yyyystringValue ,因为格式化程序无法确定哪个值代表什么,它假定并校正了月份为20 ,但是滚动年份。

A simple check against this is to compare the resulting Date with the String by formatting the Date with the original formatter, for example... 对此的一个简单检查是通过使用原始格式程序格式化Date来比较生成的DateString ,例如...

public java.util.Date convertStringToDate(String stringValue) {
    String[] formatStrings = {"dd/MM/yy", "dd-MM-yy", "dd-MMM-yyyy"};

    for (String formatString : formatStrings) {
        try {
            DateFormat df = new SimpleDateFormat(formatString);
            java.util.Date date = df.parse(stringValue);

            if (df.format(date).equals(stringValue)) {
                System.out.println(formatString + "; " + stringValue + "; " + date);
                return date;
            }
        } catch (ParseException e) {

        }
    }

    return null;

}

Which now returns null . 现在返回null

However, if I add MM/dd/yyyy to the formatStrings ( String[] formatStrings = {"dd/MM/yy", "dd-MM-yy", "dd-MMM-yyyy", "MM/dd/yyyy"}; ) in the convertStringToDate method, it will return 20/03/2020 但是,如果我将MM/dd/yyyy添加到formatStringsString[] formatStrings = {"dd/MM/yy", "dd-MM-yy", "dd-MMM-yyyy", "MM/dd/yyyy"}; )在convertStringToDate方法中,它将返回20/03/2020

java.time java.time

You may want to checkout the java.time package and DateTimeFormatter class. 您可能需要检出java.time包和DateTimeFormatter类。 ( Tutorial ) 教程

The original java date and time utilities suffer a number of deficiencies making them prone to programmer error. 原始的Java日期和时间实用程序存在许多缺陷,使其易于出现程序员错误。

java.time has immutable objects and other thoughtful design. java.time具有不可变的对象和其他周到的设计。 It's the new de-facto standard. 这是新的事实上的标准。

For example: 例如:

String date_string = "03/20/2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate parsedDate = LocalDate.parse(date_string, formatter);

wouldn't silently fail. 不会默默地失败。 Instead, it throws the exception: 相反,它将引发异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '03/20/2020' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 20

and the debugging would likely have gone much more quickly... 而且调试可能会快得多...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM