First don’t keep your order date in a string. Since you want the order time, keep it in an Instant
. An Instant
is a point in time independent of time zone or UTC offset (some say that it’s in UTC). You can always format into a string in the user’s time zone later when you need it for presentation. It’s the same as numbers and Boolean values, you don’t keep those in strings (I hope).
Second use java.time for your date and time work. The Instant
class I mentioned belongs to java.time.
Third don’t pretend that GMT-4:00 is a time zone. It’s a GMT offset. Your users may use a different GMT offset about any time soon when summer time (DST) begins or ends or the politicians just change their minds about which GMT offset to belong to. Therefore use a proper time zone ID like America/Barbados. The format is region/city.
So your method gets simple:
public Instant getOrderDate() {
return Instant.now();
}
To add a day — to get the same time tomorrow — you need first to decide on a time zone since in some time zones the day may be for example 23 or 25 hours long sometimes. I suppose you want to take this into account and not just blindly add 24 hours. So for example:
ZoneId zone = ZoneId.of("Africa/Windhoek");
ZonedDateTime orderDateTime = getOrderDate().atZone(zone);
ZonedDateTime tomorrow = orderDateTime.plusDays(1);
String tomorrowInIso8601Format = tomorrow.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(tomorrowInIso8601Format);
Output when I ran just now:
2021-01-07T19:01:39.281591+02:00
I am exploiting the fact that the formatter is built in.
Link
Oracle tutorial: Date Time explaining how to use java.time.