gpt4 book ai didi

java - 在java中转换时获取不同格式的日期

转载 作者:行者123 更新时间:2023-11-30 08:06:43 26 4
gpt4 key购买 nike

早上好,我只有一个问题,下面是执行时年份发生变化的程序。假设输入日期是 03/20/2020,然后是执行日期,程序显示为 03/08/2021,这是完全错误的。随着年份的增加,完整的日期是错误的。请告知我如何更正我的程序以达到相同的日期。

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;

}

}

最佳答案

你原来的 String 日期似乎是 MM/dd/yyyy 的格式,extractDate 使用,但是你的 convertStringToDate 使用 dd/MM/yyyy 格式。

SimpleDateFormat 使用模式 dd/MM/yyyy 来解析 stringValue 实际上是 MM/dd/yyyy ,因为格式化程序无法确定哪些值代表什么,它假定并更正月份为 20,但滚动年份。

一个简单的检查是将生成的 DateString 进行比较,例如,通过使用原始格式化程序格式化 Date。 ..

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;

}

现在返回 null

但是,如果我将 MM/dd/yyyy 添加到 formatStrings (String[] formatStrings = {"dd/MM/yy", "dd -MM-yy", "dd-MMM-yyyy", "MM/dd/yyyy"};) 在 convertStringToDate 方法中,它将返回 20/03/2020

关于java - 在java中转换时获取不同格式的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34170914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com