Reputation: 1085
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
Upvotes: 0
Views: 77
Reputation: 338564
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
LocalDate
For a date-only value without time-of-day and without time zone, use LocalDate
class.
LocalDate.parse( "2021-04-01" )
ZonedDateTime
If you want to represent the first moment of the day for that date in a particular time zone, apply ZoneId
to get a ZonedDateTime
.
Do not assume the day starts at 00:00:00 🕛. Some dates in some zones start at another time such as 01:00:00 🕐. So let java.time determine the first moment.
EDT
is not a real time zone. Perhaps you meant America/Montreal
, America/New_York
, America/Indiana/Marengo
, or some such.
LocalDate ld = LocalDate.parse( "2022-01-23" ) ;
ZoneId z = ZoneId.of( "America/Indiana/Marengo" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Upvotes: 2