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,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
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.
Advertisement
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);