-3

I am developing an android apps currently, in some of my function required to get the date time from the phone, but assuming user may change their phone date time at their willing, in this case my application will display wrong result. I am using timestamp as the data type for my date time btw, so how to ensure that I am getting the most accurate date time from the phone without concerning user modify the phone date time.

Calendar dateTime=Calendar.getInstance(); long milliseconds=dateTime.getTimeInMillis();

As you see the code above is getting date time from the phone itself which means it may inaccurate due to user modify their date time in the phone. Anyone please toss an solution or idea to me about how to do this is correct way. Thx and Sorry for my broken english

the Calendar : it's based on the device time settings/timezone. Quote from the doc: "Calendar's getInstance method returns a calendar whose locale is based on system settings and whose time fields have been initialized with the current date and time"

but for my question is what if user change the time settings??

Thomas Law
  • 182
  • 1
  • 2
  • 12
  • Possible duplicate of [Get current time and date on Android](https://stackoverflow.com/questions/5369682/get-current-time-and-date-on-android) – RonTLV Sep 23 '17 at 09:42
  • 1
    You'd need to query the time from an outside web service, but if the user sets their phone to the wrong date and time, they probably need to accept that their apps that rely on the phone's time won't work properly. – JJJ Sep 23 '17 at 09:45
  • do you have any link or documentation that related to this can share me? I really no idea how to implement a web service to apps for getting the accurate time without interference by the user – Thomas Law Sep 23 '17 at 09:49
  • You can get properly date and time from the internet. [Example](https://stackoverflow.com/a/13547204/3166697) – Dima Kozhevin Sep 23 '17 at 09:51
  • @DimaKozhevin sounds like the correct way, thank you btw, I will try on this – Thomas Law Sep 23 '17 at 09:54
  • This question is already answered here https://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java – Saitejareddy Feb 16 '22 at 14:45

1 Answers1

-1
Date d = new Date();
DateFormat date = new SimpleDateFormat("dd MMM yy - HH:mm");
Log.i("Date",date.format(d));

edit :

Send request to somewhere and read date from it Request:

HEAD / HTTP/1.1
Host: google.com

Response:

HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Wed, 09 Mar 2011 16:04:48 GMT
Expires: Fri, 08 Apr 2011 16:04:48 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block

Edited again : use this code for request and get the date

URL obj = new URL("http://mkyong.com");
URLConnection conn = obj.openConnection();
String date = conn.getHeaderField("date");