-4

I am trying to get current UTC date time in millis. But every code I used for this returns me the device's current date time. When I chenge my device's date, time it shows me chenged one. So, I want to get GMT/UTC date time so that it will show me correct date even if user changes the date, time of his/her device.

Codes I tried:

Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();

and

DateFormat df = DateFormat.getTimeInstance();
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        String gmtTime = df.format(new Date());
        Date gmtDate = df.parse(gmtTime);

Actually I want to set an alarm at November 15 2017, 5 PM using AlarmManager, receive that event hide some activities in my app which I don't want to show after this date, time.

How can I acheive this?

Thanks in advance!

Vrushali Sabnis
  • 197
  • 2
  • 12

4 Answers4

3

Use this ....

Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInM‌​illis()

for eg.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long timeInMili = calendar .getTimeInMillis();

or

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
long timeInMili = calendar .getTimeInMillis();
Mohd Saquib
  • 580
  • 4
  • 14
  • 1
    getTimeMillis() returns "the current time as UTC milliseconds from the epoch". So setting different timezones won't change the result. – shervinox Feb 27 '21 at 12:14
0

Try TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);

Anton Potapov
  • 1,265
  • 8
  • 11
0
long timestampMilliseconds =System.currentTimeMillis();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String stringDate = simpleDateFormat.format(new Date(timestampMilliseconds));
    System.out.println(stringDate);

if do you want to get as utc just change the time zsone

Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34
0

There is no way to get the correct time from device independently, If you are using Google Location Provider then getTime() will return derived time from GPS signal, else use server time.

Rahul
  • 1,380
  • 1
  • 10
  • 24