0

I have variable curTime, I want to get the current time of the form 1616572689, there are 2 familiar methods

val curTime: Long = Date().getTime()

or

val curTime = System.currentTimeMillis()

But here's the problem, if I change the time on the phone for example to 2007, then the value of the variable will be incorrect! It will show the year 2007. How do I make sure that the data is taken not from the system, but from the Internet? some site, for example https://timestamp.online/

Please help, couldn't find anything about this problem.

1 Answers1

1

You find an online server with a public API for retrieving the current time, e.g. World Time API. That's just an example, there are other servers, and you should do your own research to find which server best fits your needs and licensing restrictions.

You then perform an HTTP GET request and parse the returned JSON to get the value you seek.

E.g. if you want the current time for US Eastern time zone, you do and HTTP GET from http://worldtimeapi.org/api/timezone/America/New_York, which will respond with something like this:

{
  "abbreviation": "EDT",
  "client_ip": "73.106.239.191",
  "datetime": "2021-03-28T06:37:10.320418-04:00",
  "day_of_week": 0,
  "day_of_year": 87,
  "dst": true,
  "dst_from": "2021-03-14T07:00:00+00:00",
  "dst_offset": 3600,
  "dst_until": "2021-11-07T06:00:00+00:00",
  "raw_offset": -18000,
  "timezone": "America/New_York",
  "unixtime": 1616927830,
  "utc_datetime": "2021-03-28T10:37:10.320418+00:00",
  "utc_offset": "-04:00",
  "week_number": 12
}

The value you're looking for is the unixtime field.

Andreas
  • 154,647
  • 11
  • 152
  • 247