0

When converting back to a Date from a formatted date string, SimpleDateFormat returns incorrect Date. Test code:

import java.util.*;
import java.text.SimpleDateFormat;

public class DateTest {

     public static void main(String []args) throws Exception {
                SimpleDateFormat formatter = new SimpleDateFormat("EEEE dd MMMM YYYY hh:mm:ssa");
                System.out.println("Week Year Support: " + formatter.getCalendar().isWeekDateSupported());                
                Date origDate = new Date(120, 1, 1);
                String dateStr = formatter.format(origDate);                    
                Date reverseDate = formatter.parse(dateStr);
                System.out.println(origDate + "\t" + dateStr + "\t" + reverseDate);
     }
}

Output:

Week Year Support: true
Sat Feb 01 00:00:00 UTC 2020    Saturday 01 February 2020 12:00:00AM    Sat Jan 04 00:00:00 UTC 2020
Vinod
  • 356
  • 3
  • 6
  • 1
    Did you consider switching over to the "new" java.time api? – Thomas Mar 29 '21 at 06:06
  • Btw, this should help: [How does Java “week year” really work?](https://stackoverflow.com/questions/34691582/how-does-java-week-year-really-work). Citing the accepted answer: "On parsing, SimpleDateFormat expects a matching set of values: either day, month, year **or** day of week, week in year, week-year." – Thomas Mar 29 '21 at 06:21
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 29 '21 at 06:24
  • Your format does not make sense. Week-based year is only useful with a week number. – Ole V.V. Mar 29 '21 at 06:25

0 Answers0