[英]Getting different format of date while conversion in java
早上好,我只有一個查詢,下面是執行年份會更改的程序。 比方說,日期為輸入是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
來解析實際在MM/dd/yyyy
的stringValue
,因為格式化程序無法確定哪個值代表什么,它假定並校正了月份為20
,但是滾動年份。
對此的一個簡單檢查是通過使用原始格式程序格式化Date
來比較生成的Date
與String
,例如...
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.time包和DateTimeFormatter類。 ( 教程 )
原始的Java日期和時間實用程序存在許多缺陷,使其易於出現程序員錯誤。
java.time具有不可變的對象和其他周到的設計。 這是新的事實上的標准。
例如:
String date_string = "03/20/2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate parsedDate = LocalDate.parse(date_string, formatter);
不會默默地失敗。 相反,它將引發異常:
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
而且調試可能會快得多...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.