-1

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 :)

Capt Wilco
  • 11
  • 1
  • 1
    Have you tried anything? If not, find out about `java.time`, otherwise please show us your attemtp(s) in code. – deHaar May 26 '21 at 06:55
  • 1
    Follow the link https://www.java67.com/2016/04/how-to-convert-string-to-localdatetime-in-java8-example.html – Md Kawser Habib May 26 '21 at 08:34
  • Does this answer your question? [How to convert UTC DateTime to another Time Zone using Java 8 library?](https://stackoverflow.com/questions/54108388/how-to-convert-utc-datetime-to-another-time-zone-using-java-8-library) – Ole V.V. Jun 20 '21 at 08:39

2 Answers2

1

Use java.time classes:

  • DateTimeFormatter to parse (and format)
  • LocalDateTime to represent the given input
  • ZonedDateTime to include the GMT time zone,
    and convert to another zone
  • if needed, DateTimeFormatter to format as string

Example:

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

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
snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android look into [desugaring](https://developer.android.com/studio/write/java8-support-table) or see [How to use ThreeTenABP …](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. May 27 '21 at 12:24