2

I am trying to get UTC time in my application but unfortunately every time I am getting my current emulator Date and Time Instead of UTC.

Tried,

  1. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

  2. ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);

  3. DateTime now = DateTime.now(DateTimeZone.UTC);

My code:

//create UTC time
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    System.out.println("DATETIME ==> " + cal.getTime());
    ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
    System.out.println("DATETIME = " + utcTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    DateTime now = DateTime.now(DateTimeZone.UTC);
    System.out.println("DATETIME = " + now);

Any help highly appreciated.

Vatsal Dholakiya
  • 545
  • 4
  • 19

1 Answers1

2

Try this code:

private String getCurrentDateTimeAccordingToUTC(String format) {
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return simpleDateFormat.format(date);
}


String date = getCurrentDateTimeAccordingToUTC("dd-MM-yyyy hh:mm:ss a");
Log.e("date--","inUTC--:"+date);
Android Geek
  • 8,956
  • 2
  • 21
  • 35
  • Got this UTC time:==> 2021-07-26T15:05 but Actually UTC date is ==> 27 and I am getting 26 which is my emulator date. – Vatsal Dholakiya Jul 27 '21 at 06:04
  • Conversion of date time is dependent on current date time of device. – Android Geek Jul 27 '21 at 06:14
  • But I don't want to conversion I want Actual UTC time. – Vatsal Dholakiya Jul 27 '21 at 06:19
  • 1
    Check this project - https://github.com/instacart/truetime-android, for getting actual UTC date time without dependent on device time – Android Geek Jul 27 '21 at 06:59
  • 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.) – Ole V.V. Aug 01 '21 at 08:10