The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.
From your question, I concluded that your time-zone offset is -04:00
. You can apply the fixed offset to achieve what you want.
Demo:
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
Stream.of("2022-11-02", "0001-01-01")
.map(LocalDate::parse)
.map(date -> date.atStartOfDay())
.map(ldt -> ldt.atOffset(ZoneOffset.of("-04:00")))
.map(odt -> odt.withOffsetSameInstant(ZoneOffset.UTC))
.map(OffsetDateTime::toInstant)
.forEach(System.out::println);
}
}
Output:
2022-11-02T04:00:00Z
0001-01-01T04:00:00Z
For the formatted output, you can use DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx")
as shown below:
class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx", Locale.ENGLISH);
Stream.of("2022-11-02", "0001-01-01")
.map(LocalDate::parse)
.map(date -> date.atStartOfDay())
.map(ldt -> ldt.atOffset(ZoneOffset.of("-04:00")))
.map(odt -> odt.withOffsetSameInstant(ZoneOffset.UTC))
.map(odt -> odt.format(formatter))
.forEach(System.out::println);
}
}
Output:
2022-11-02T04:00:00.000+00:00
0001-01-01T04:00:00.000+00:00
Learn more about the modern Date-Time API from Trail: Date Time.