I want to parse a Date from a String in NYC timezone, add 1 day and then output string.
like:
- parse to date
- add 1 day
- output
The problem is, that when I parse a date during the adjustment for daylight saving, the day in step 1 already will have extra hour and when I add 1 day, the next day will have that extra hour which is wrong for the next day, due next Day is not the day when daylight saving adjustment happens.
example:
input date March 10 2am
parsed date: March 10 3am
add 1 day => March 11 3am // has to be March 11 2am
But if you parse directly March 11 2am, then it's correct:
input date March 11 2am
parsed date => March 11 2am
So, I need to parse a Date, add 1 day and only after that execute that smart adjustment:
input date March 10 2am
parsed date: March 10 2am //do not be smart here, still 2 am
add 1 day => March 11 2am // here you can be smart and adjust for daylight saving if needed
this code is incorrect and shows 7am March 11 instead of 6am
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class MainApp {
public static void main(String[] args) {
try {
SimpleDateFormat in = new SimpleDateFormat("yyyyMMdd-HH.mm");
in.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date date = in.parse("20240310-02.00");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
date = calendar.getTime();
System.out.println(in.format(date)); // prints 20240311-03.00, but has to be 20240311-02.00
//parse 11 march directly, works ok
Date date2 = in.parse("20240311-02.00");
System.out.println(in.format(date2)); // prints 20240311-02.00
} catch (ParseException e) {e.printStackTrace();}
}
}