I have a datetime string with the format of
String date = "2021-05-26 14:23" // GMT Time
Now my question is how can I convert in to local time its the GMT time..? Thanks in Advance :)
I have a datetime string with the format of
String date = "2021-05-26 14:23" // GMT Time
Now my question is how can I convert in to local time its the GMT time..? Thanks in Advance :)
Use java.time
classes:
DateTimeFormatter
to parse (and format)LocalDateTime
to represent the given inputZonedDateTime
to include the GMT time zone,DateTimeFormatter
to format as stringExample:
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
var input = LocalDateTime.parse(date, formatter).atZone(ZoneId.of("GMT"));
this can now be changed to another zone using withZoneSameInstant(...)
and then, if desired, changed toLocalTime()
or toLocalDateTime()
; or format(...)
to text.
you can convert String
date/time to more universal timestamp with
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
long timestampGmt = sdf.parse(date).getTime(); // as timestamp
int offset = TimeZone.getDefault().getRawOffset() +
TimeZone.getDefault().getDSTSavings(); // currently set time zone offset
long timestampCurrent = timestampGmt - offset;
String newDate = sdf.format(timestampCurrent); // again to string with same structure