-1

I stumbled upon a idea below and wanted to know your opinion:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

If the user's computer is set to a wrong date, does this is print out wrong date. From where does the JVM captures the date ? How to make sure that Date is always printed correctly even when the end user has adjusted his date?

Yogesh D
  • 1,558
  • 14
  • 29
R Penumaka
  • 171
  • 7
  • 6
    It uses the system's date so yes, if you modify it, the JVM has no way to tell it isn't the good one :) – Arnaud Nov 23 '16 at 16:15
  • 2
    ``new Date()`` sets the internal value of the timestamp to ``System.currentTimeMillis()``. – f1sh Nov 23 '16 at 16:15
  • 4
    The user's own set time _is_ the correct time, because that's the time which they are utilizing. If you're offline, and your computer time had to be manually set, how would you determine a "correct" time out of nowhere? – Rogue Nov 23 '16 at 16:15
  • Please search Stack Overflow before posting. – Basil Bourque Nov 24 '16 at 03:23

2 Answers2

2

java relies on the system clock, so if the user has misconfigured their time, timezone, date etc that is what you'll see.

having said that, if your code can assume a working internet connection you could maybe use some java NTP implementation to connect to internet time servers and get the correct time.

see more info here - How to use an Internet time server to get the time?

if you dont require the degree of precision that NTP offers and want something simpler you could hit up any number of rest APIs that serve time - here is one

Community
  • 1
  • 1
radai
  • 23,949
  • 10
  • 71
  • 115
  • What about sysdate from oracle DB ? – R Penumaka Nov 29 '16 at 16:11
  • @RPenumaka - as per the doc (https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions172.htm) - "returns the current date and time set for the operating system on which the database resides". basically no infrastructure service process can assume a working internet connection always and so they all go for the OS clock. – radai Nov 30 '16 at 00:05
1

JVM will capture the date from the System. If you set it incorrect it will give you incorrect timings. Still if you would like to have correct timings, you can use any REST API's which will pick up correct date, time according to your timezone from the internet.

You can get free APIs from TimeZone

Community
  • 1
  • 1
Yogesh D
  • 1,558
  • 14
  • 29