17

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?

ltlBeBoy
  • 1,242
  • 16
  • 23
Amit
  • 33,847
  • 91
  • 226
  • 299
  • 2
    Date is a relative thing... There is no such thing as "correct current date", unless you are referring to a specific time zone. – Eyal Schneider May 23 '10 at 12:11
  • ok.. how can I get the correct date and time of a particular timezone? – Amit May 23 '10 at 12:12
  • You have to start with the date and time of your current system - is that OK? – mmmmmm May 23 '10 at 12:14
  • 3
    Why on earth would you not regularly synch the system clock with NTP?! It's a *solved problem*. Even if the thing goes regularly offline, the system clock shouldn't drift that much that it *gets the freaking **year** wrong*! – Donal Fellows May 23 '10 at 12:21
  • 3
    @Donal you don't know why Yatendra wants to do this. Maybe (s)he has written software that has a trial period, and it should be disabled after a certain date. In that case you can't trust the local system date and time, because a user could have deliberately tampered with it to make the software still work after the trial expiry date. – Jesper May 23 '10 at 14:39

6 Answers6

41

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
john_science
  • 6,325
  • 6
  • 43
  • 60
  • 9
    Wow, 29 upvotes and it doesn't answer the question, which specifically asked how to get the real date when the system clock is wrong. – Paul Tomblin Jan 01 '17 at 23:39
  • @Paul Tomblin The original title of this question was "Java - How to get current year?" which does not match the actual question. Modified that. – ltlBeBoy Feb 21 '18 at 12:37
  • 1
    @ltlBeBoy I guess it's too much to expect question answerers and upvoters to read more than the title. – Paul Tomblin Feb 22 '18 at 12:37
7

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);
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
4

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.

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
3

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.

Dewfy
  • 23,277
  • 13
  • 73
  • 121
0

The programming level methods are developed to Get Date and Time from your system itself. You cannot modify them to get the dates except than the System specified.

For your additional requirement, if you wish to really have it, you would require a Synchronization between your Client Machine and Server.

Mr.Expert
  • 466
  • 2
  • 3
0

Here's some code to fetch the date in HTTP format (usually UTC timezone) from a web server of your choice.

Of course, if you have no control over the physical hardware and OS, nothing can guarantee you will be able to talk to the actual web server you ask for... but anyway.

package some.package;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class Test {

  private static String getServerHttpDate(String serverUrl) throws IOException {
    URL url = new URL(serverUrl);
    URLConnection connection = url.openConnection();

    Map<String, List<String>> httpHeaders = connection.getHeaderFields();

    for (Map.Entry<String, List<String>> entry : httpHeaders.entrySet()) {
      String headerName = entry.getKey();
      if (headerName != null && headerName.equalsIgnoreCase("date")) {
        return entry.getValue().get(0);
      }
    }
    return null;
  }

  public static void main(String[] args) throws IOException {
    String serverUrl = args.length > 0 ? args[0] : "https://google.com";
    System.out.println(getServerHttpDate(serverUrl));
  }

}
Cosimo
  • 2,846
  • 1
  • 24
  • 26