![SimpleDateFormat incorrectly rolling year forward during format of Date [duplicate]](https://www.xszz.org/skin/wt/rpic/t7.jpg)
Question:
This question already has an answer here:
<ul><li> <a href="/questions/43933597/eee-mmm-dd-hhmmss-zzz-yyyy-date-format-to-java-sql-date" dir="ltr" rel="nofollow">“EEE MMM dd HH:mm:ss ZZZ yyyy” date format to java.sql.Date</a> <span class="question-originals-answer-count"> 1 answer </span> </li> </ul>I am currently working with a DateUtils class, that helps format dates across a system. I have a Date in format yyyyMMdd, which is parsed from a String.
I pass into another format to receive a "period" value, of format E d MMM YY.
The below, should give me a period of MON 31 DEC 18. However it is returning MON 31 DEC 19. Why is the year rolling forward?
Thanks
final SimpleDateFormat dateFormat_E_d_MMM_YY = new SimpleDateFormat("E d MMM YY");
final SimpleDateFormat dateFormat_yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
final Date date = dateFormat_yyyyMMdd.parse("20181231");
System.out.println(date);
System.out.println(dateFormat_E_d_MMM_YY.format(date));
Answer1:You have a typo use E d MMM yy
instead of E d MMM YY
.
From the docs :
<blockquote>y : year
Y : Week year
</blockquote> Answer2:You have written YY
which means week.
You need the year, hence you will need to write yy
In case you need more details you can check all the meaning of the different variables in the documentation of <a href="https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html" rel="nofollow">SimpleDateFormat</a> class.
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10