[英]Java: having issues to parse object.toString to LocalDate using java.time
我正在處理一個問題集,並試圖構建一個返回日期的類。 對於這個問題,我需要返回給定日期的星期幾,例如“星期一”、“星期二”。 我在 Stack Overflow 上搜索,並決定嘗試使用 java.time:
package Chapter1.Section2;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class exercise_1_2_12 {
private int day;
private int month;
private int year;
public exercise_1_2_12(int month, int day, int year){
if (!isDateValid(month, day, year)){
throw new IllegalArgumentException("Invalid Date!");
}
this.month = month;
this.day = day;
this.year = year;
}
public int day(){
return day;
}
public int month(){
return month;
}
public int year(){
return year;
}
public String toString(){
//return month() + "-" + day() + "-" + year();
return year + "/" + String.format("%02d", month) + "/" +
String.format("%02d", day);
}
public boolean isDateValid(int month, int day, int year) {
int[] dayInEachMonthLeapYr = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] dayInEachMonthNonLeapYr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
boolean valid = true;
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
if (year < 1 || month < 1 || month > 12 || day < 1 || day > dayInEachMonthLeapYr[month - 1]) {
valid = false;
}
} else {
if (year < 1 || month < 1 || month > 12 || day < 1 || day > dayInEachMonthNonLeapYr[month - 1]) {
valid = false;
}
}
return valid;
}
public String dayOfWeekName(){
DateTimeFormatter format = DateTimeFormatter.ofPattern("mm/dd/yyyy");
String input = this.toString();
LocalDate date = LocalDate.parse(input, format);
DayOfWeek dayOfWeek = date.getDayOfWeek();
String result = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.US);
return result;
}
public static void main(String[] args){
StdOut.print("Enter month: ");
int month = StdIn.readInt();
StdOut.print("Enter day: ");
int day = StdIn.readInt();
StdOut.print("Enter year: ");
int year = StdIn.readInt();
exercise_1_2_12 smartDate = new exercise_1_2_12(month,day,year);
StdOut.println(smartDate);
smartDate.dayOfWeekName();
}
}
問題可能出在實例方法 dayOfWeekName() 中,我嘗試解析對象 this。 到String格式,然后存儲在LocalDate日期中,然后返回工作日的名稱。 我測試了一下,報錯信息如下:
Enter month: 4
Enter day: 1
Enter year: 2018
2018/04/01
Exception in thread "main" java.time.format.DateTimeParseException: Text '2018/04/01' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at Chapter1.Section2.exercise_1_2_12.dayOfWeekName(exercise_1_2_12.java:64)
at Chapter1.Section2.exercise_1_2_12.main(exercise_1_2_12.java:85)
Process finished with exit code 1
我不太確定如何解決這個問題。
使用這個格式化程序:
DateTimeFormatter.ofPattern("MM/dd/yyyy")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.