How to get perfect UTC Time in java/android?



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.

Answer

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


Source: stackoverflow