Here I am trying to parse two dates in java. Date 1 is "2021-01-01" and date 2 is "2021-04-01". But after parsing Java generating Date object with a different timezone. Really confused by this behavior. I am looking at the same timezone and that is EDT.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateCalculation {
private static final DateFormat formater = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
public static void main(String args[]) throws ParseException {
Date date1 = getDateFromString("2021-01-01");
System.out.println("Date 1: " + date1);
Date date2 = getDateFromString("2021-04-01");
System.out.println("Date 2: " + date2);
}
public static Date getDateFromString(String dateString) throws ParseException {
if(dateString == null || dateString.trim().length() == 0)
return null;
dateString = dateString.replace("\"", ""); // Remove quotes
return formater.parse(dateString);
}
}
Output:
Date 1: Fri Jan 01 00:00:00 EST 2021
Date 2: Thu Apr 01 00:00:00 EDT 2021
Date#toStringis using an internal formatter, oh, and you should be using thejava.timeAPI over the olderjava.utilbased date classesDateclass was behaving (andSimpleDateFormatwas even worse). I say ‘was’ because the good solution, really the only sensible solution is to stop using those classes and switch to java.time, the modern Java date and time API.Dateand related classes are long outdated.