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?
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
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With