I am trying to convert date from one format to another, the date entered is in this format : 'mm-dd-yyyy' to 'yyyy-mm-dd'.
I received the date from webpage in 'mm-dd-yyyy' format and when I insert this date in MySQL using Hibernate, the date changes to some anonymous value.
import java.io.*;
import java.text.*;
import java.util.*;
class test{
public static void main(String... s) throws Exception{
Date date ;
String datestr;
DateFormat dateFormat1 = new SimpleDateFormat("mm-dd-yyyy");
DateFormat dateFormat2 = new SimpleDateFormat("yyyy-mm-dd");
date = dateFormat1.parse("01-01-2015");
datestr = dateFormat1.format(date);
System.out.println(date);
System.out.println(datestr);
date = dateFormat2.parse(datestr);
datestr = dateFormat2.format(date);
System.out.println(date);
System.out.println(datestr);
}
}
Expected output:
Thu Jan 01 00:00:00 IST 2015 2015-01-01
Actual output:
Thu Jan 01 00:01:00 IST 2015 01-01-2015 Thu Jul 08 00:01:00 IST 6 0006-01-08
The time of day is 00:01 instead of 00:00, and the latter date is a mystery.
LocalDatefrom java.time, the modern Java date and time API, for a date andDateTimeFormatterfor parsing it.java.util.Datehad design problems,DateFormatandSimpleDateFormatwere notorious trouble makers, and all had already been supplanted by java.time 10 years ago, before this question was asked.