问题
I am attempting to parse date using SimpleDateFormat. The date is parsed successfully but the output date format is incorrect or deducted by a year, The Date method that uses SimpleDateFormat is shown below
public Date parseDate(String date) {
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD",Locale.ENGLISH);
Date parsedDate = null;
try {
parsedDate = format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return parsedDate;
}
Here is the sample image parsed
Date start = parseDate(dateVal); // dateVal sample is 2020-09-25
When the date is parsed, this is the output
Sun Dec 29 00:00:00 WAT 2019
My challenge is to return a date sample of - 2020-09-25 after parsing
回答1:
You have used the wrong symbols. Use yyyy-MM-dd
instead of YYYY-MM-DD
. Note that DD
stands for the Day of the year and Y
stands for Week year. Check the documentation to learn more about it.
Also, I recommend you switch from the outdated and error-prone java.util
date-time API and SimpleDateFormat
to the modern java.time
date-time API and the corresponding formatting API (package, java.time.format
). Learn more about the modern date-time API from Trail: Date Time.
If you are using Android and your Android API level is still not compliant with Java8, check How to use ThreeTenABP in Android Project and Java 8+ APIs available through desugaring.
Using modern date-time API:
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2020-09-25");
System.out.println(date);
}
}
Output:
2020-09-25
Note that since your date-time string is already in the ISO8601 format, you do not need to use any DateTimeFormatter
while parsing it to LocalDate
as it is the default pattern used by LocalDate#parse.
Using the legacy date-time API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2020-09-25");
System.out.println(date);
}
}
回答2:
You can do it like so:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
parsedDate = format.parse(date);
You should be using parse(String)
instead of parseDate()
来源:https://stackoverflow.com/questions/64071686/simpledate-formater-to-format-returns-incorrect-deducted-date-after-formating