Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to get current date independent from system date? [duplicate]

I want to know the current Date and Time.

The code

Calendar.getInstance();

represents a date and time of the system on which the program is running and the system date can be wrong.

So Is there any way by which I can get correct current date and time irrespective of the date and time of the system on which program is running?

like image 415
Yatendra Avatar asked May 23 '10 12:05

Yatendra


4 Answers

In versions of Java prior to 1.1 it was standard to use the Date class:

Date now = new Date();     // Gets the current date and time
int year = now.getYear();  // Returns the # of years since 1900

However, in newer versions of Java, much of the Date class has been deprecated (specifically the getYear method). It is now more standard to use the Calendar class:

Calendar now = Calendar.getInstance();   // Gets the current date and time
int year = now.get(Calendar.YEAR);       // The current year
like image 155
john_science Avatar answered Oct 08 '22 10:10

john_science


I don't understand completely your question but I can answer your title:

GregorianCalendar gc = new GregorianCalendar(System.getCurrentTimeMillis());
int year = gc.get(Calendar.YEAR);
like image 32
Martijn Courteaux Avatar answered Oct 08 '22 10:10

Martijn Courteaux


If you're on the internet, you might be able to ask a known and trusted time source. If the person running your program wants to prevent your program from doing that (like if you've given them a time limited license and they don't want to pay for more time), they might spoof or block that connection.

On one project I was on, we placed a secure, trusted time source in the hardware that could not be tampered with. It was designed for encryption and licensing, and had a Java library to access it. Sorry, I can't remember the name of the device.

So the answer is maybe yes, maybe no.

like image 23
Paul Tomblin Avatar answered Oct 08 '22 10:10

Paul Tomblin


Have your system Internet access? If so, you can use synchronization with precise time services (for example: http://tldp.org/HOWTO/TimePrecision-HOWTO/ntp.html) and grant that you want.

like image 22
Dewfy Avatar answered Oct 08 '22 10:10

Dewfy