Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
Vatsal Dholakiya Avatar asked Aug 28 '26 07:08

Vatsal Dholakiya


1 Answers

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);
like image 170
Android Geek Avatar answered Aug 30 '26 21:08

Android Geek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!