I’m not finding a way to do edit GMT Date
I receive “params.date” one string in this format “yyyyMMdd”, so this is my flow:
Date date = new SimpleDateFormat('yyyyMMdd').parse(params.data) System.out.println(sdf.parse(params.data))
output:
Thu Nov 17 21:00:00 GMT-03:00 2022
And I need it:
Thu Nov 17 21:00:00 GMT-00:00 2022
Can someone help me?
Advertisement
Answer
A few important points:
- Thu Nov 17 21:00:00 GMT-03:00 2022 is not equal to Thu Nov 17 21:00:00 GMT-00:00 2022. The date-time of Thu Nov 17 21:00:00 GMT-03:00 2022 is equal to the date-time of Fri Nov 18 00:00:00 GMT+00:00 2022 which you can obtain by adding 3 hours to Thu Nov 17 21:00:00 GMT-03:00 2022.
- Your time-zone has an offset of -03:00 and therefore the
java.util.Date
object is being displayed with the default time-zone offset. Note thatjava.util.Date
does not represent a real date-time, rather, it gives you the number of milliseconds from the Epoch and then theDate#toString
implementation applies the system’s time-zone to render the string. - 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.
Demo with java.time API:
import java.time.LocalDate; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class Main { public static void main(String[] args) { String data = "20221118"; LocalDate date = LocalDate.parse(data, DateTimeFormatter.BASIC_ISO_DATE); ZonedDateTime zdt1 = date.atStartOfDay(ZoneOffset.UTC); ZonedDateTime zdt2 = zdt1.withZoneSameInstant(ZoneOffset.of("-03:00")); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss 'GMT'xxx uuuu", Locale.ENGLISH); System.out.println(formatter.format(zdt2)); System.out.println(formatter.format(zdt1)); } }
Output:
Thu Nov 17 21:00:00 GMT-03:00 2022 Fri Nov 18 00:00:00 GMT+00:00 2022
Learn more about the modern Date-Time API from Trail: Date Time.