Java: Get Current Date and Time from Server Not System Clock

Java: Get current Date and Time from Server not System clock

Local network

If your machine is connected to a local network, connect to some machine acting as a trustworthy time server. You could write your own such time server.

Network Time Protocol

Or you could use the well-worn Network Time Protocol (NTP) with existing server and client implementations bundled with most any OS. For more on this, see the accepted Answer by aioobe.

Consider placing that time server computer in network’s DMZ so as to updates from time servers on the Internet such as the pool.ntp.org project or those provided by the United States federal government (NIST).

Internet

If your machine is connected to the internets, connect to a trustworthy time server. As discussed above, use a custom protocol such as a web service, or use NTP.

This is discussed in the Question, how to make my java app get global time from some online clock.

See also Questions: Java NTP client, and Java client for time server, such as Network Time Protocol (NTP).

Radio Clock

Obtain a radio clock with a USB connection for output of current time synchronized by a time code transmitted by a radio transmitter connected to a time standard such as an atomic clock. Transmitters are broadcasting in many countries all over the world.

The Meinberg Global company, at least, offers several such devices.

photo of a couple of external radio clock devices

GPS

Similar to the radio clocks above, a receiver of GPS (Global Positioning System) signals might also capture and relay the time signal. Or perhaps GALILEO, GLONASS or other Radionavigation-satellite service.

Sundial

Position a sundial outside a window. Attach a webcam to the computer in question. Position the webcam in the window. Write an app to interpret the time of day from current image of the sundial.

photo of a sundial on a pedestal in a garden

Caveat: This solution does not function in Seattle.


java.time.Clock

To harness any of these suppliers of the current moment, write a subclass of the abstract java.time.Clock class.

You can pass your Clock implementation as an argument to the various java.time methods. For example, Instant.now( clock ).

Instant instant = Instant.now( yourClockGoesHere ) ;

For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed, offset, tick, and more.

Avoid the legacy date-time classes from the earliest versions of Java, such as Date & Calendar. These troublesome classes are entirely supplanted by the java.time classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later

    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to get the current date/time in Java

It depends on what form of date / time you want:

  • If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.

  • If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:

    • new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.

    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.

    • new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)

    • in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.

Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.

With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.


1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.

2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.

How can I get the current date and time in UTC or GMT in Java?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

If this isn't the problem, please post some sample code.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

Java - How to get current date independent from system date?

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.

How to get the current date and time of your timezone in Java?

Date is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date." Use Date in conjunction with Calendar and/or TimeZone.getDefault() to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid") to get the Madrid time zone.

... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime value, which is an instant in time in a particular calendar system and time zone.

In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.

How to get current time (NOT DEVICE)

You can get time details from internet and then use it. Just Internet is required.

Use android.net.sntp.SntpClient class.

SntpClient client = new SntpClient();
int timeout = 50000;
if (client.requestTime("time-a.nist.gov", timeout)) {
long time = client.getNtpTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
calendar.getTime(); // this should be your date
}

How to get current server time in Java?

System.currentTimeMillis() returns number of milliseconds since 1970.

If you run it on the server, you will get the server time. If you run it on the client (e.g. Applet, standalone desktop app, etc.) you will get the client time. To get the server date on the client, set up a call that returns the server time in the formatted string to the client.

If you want the date formatted a certain way , first create a Date() object and then format it using SimpleDateFormat

Date d1 = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
String formattedDate = df.format(d1);

How to get current time and date in Android

You could use:

import java.util.Calendar;
import java.util.Date;

Date currentTime = Calendar.getInstance().getTime();

There are plenty of constants in Calendar for everything you need.

Check the Calendar class documentation.

How to get the current date and time

Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

import java.util.Date;

Date d = new Date();

In the words of the Javadocs for the zero-argument constructor:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)



Related Topics



Leave a reply



Submit