I have a date that is in IST format. Which is something like the
2021-12-07T00:00:00.595+0530
I have the following code for the above output
val fromtTime = Date() val startOfDay = fromtTime.startOfDay() val dateFormat = SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" ) val startOfDate = dateFormat.format(startOfDay)
startOfDay is just and extenstion function which is something like this
fun Date.startOfDay(): Date { val now = Calendar.getInstance() now.time = this now.set(Calendar.HOUR_OF_DAY, 0) now.set(Calendar.MINUTE, 0) now.set(Calendar.SECOND, 0) return now.time }
But, what the backend really wants is in the below format with -8:00.
2021-12-07T00:00:00-08:00
Is there any way I can format it to have -08:00 in the end of the string whenever I select the timezone as “America/Los_Angeles”, because “America/Los_Angeles” is supposed to have the timezone which is -8 hours from the GMT.
Advertisement
Answer
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. Please excuse my Java syntax.
String forBackend = LocalDate.now(ZoneId.systemDefault()) .atStartOfDay(ZoneId.of("America/Los_Angeles")) .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); System.out.println(forBackend);
I ran this code in Asia/Kolkata time zone just now (within the first hour after midnight on 2021-12-08). The output was:
2021-12-08T00:00:00-08:00
A LocalDate
is a date without time of day or time zone, so LocalDate.now()
just gives us the current day in India (when Asia/Kolkata is our default time zone) without time of day. Then the call to atStartOfDay()
gives us the start if the same date in America/Los_Angeles time zone. Finally the format you asked for is built in, so we are using the predefined formatter and not writing our own format pattern string.
When summer time (DST) begins in North America, the offset will be -07:00
instead.