I was hoping to squeeze a tiny performance gain out of many calls to a function that returns a timestamp. The function looks like this:
public static long get_now_ms(){
// returns number of MILLISECONDS since epoch
java.util.Date d = new java.util.Date();
return d.getTime();
}
Can I just replace this with:
public static long get_now_ms(){
// returns number of MILLISECONDS since epoch
return System.currentTimeMillis();
}
I know that Date internally uses System.currentTimeMillis(). My question is more whether or not daylight savings time or time zone could ever lead to a difference in result with these two approaches. I imagine this may come up with Calendar objects, but not Date objects, but would love some clarification on this.
I know I will likely not see an appreciable difference in performance in a real-world application, but would nevertheless like to know the answer.
Thanks!
No difference, except for the very slight lag caused by allocating a Date object.
From the javadoc the the default constructor of Date:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
A Date is just a thin wrapper around the epoch milliseconds, without any concept of timezones. Only when rendered to a String is timezone considered, but that is handled by the Locale class.
I would suggest running a unit test (ex. https://gist.github.com/ledlogic/8532028). I saw only a slight overall benefit to running the System.currentTimeMillis versus the (new Date()).getTime().
1 billion runs: (1000 outer loops, 1,000,000 inner loops):
System.currentTimeMillis(): 14.353 seconds
(new Date()).getTime(): 16.668 seconds
Individual runs would sometimes be slightly biased toward the later approach - depending on your system activity.
No difference, and Calendar.getTimeInMillis() is also same. because the return results is the number of milliseconds since January 1, 1970, 00:00:00 GMT. you will get a same long value whereever you are all over the word.
Related
In Java, we can have many different ways to get the current timestamp, but which one is recommended:
Instant.now().toEpochMilli() or System.currentTimeMillis()
Both are fine. And neither is recommended except for a minority of purposes.
What do you need milliseconds since the epoch for?
In Java, we can have many different ways to get the current timestamp,
For current timestamp just use Instant.now(). No need to convert to milliseconds.
Many methods from the first years of Java, also many in the standard library, took a long number of milliseconds since the epoch as argument. However, today I would consider that old-fashioned. See if you can find — or create — or more modern method that takes for instance an Instant as argument instead. Go object-oriented and don’t use a primitive long. It will make your code clearer and more self-explanatory.
As Eliott Frisch said in a comment, if this is for measuring elapsed time, you may prefer the higher resolution of System.nanoTime().
If you do need milliseconds since the epoch
Assuming that you have good reasons for wanting a count of milliseconds since the epoch, …
which one is recommended: Instant.now().toEpochMilli() or
System.currentTimeMillis()[?]
Opinions differ. Some will say that you should use java.time, the modern date and time API, for all of your date and time work. This would imply Instant here. Unsg java.time is generally a good habit since the date and time classes from Java 1.0 and 1.1 (Date, Calendar, TimeZone, DateFormat, SimpleDateFormat and others) are poorly designed and now long outdated, certainly not any that we should use anymore. On the other hand I am not aware of any design problem with System.curremtTimeMillis() in particular (except what I mentioned above about using a long count of milliseconds at all, which obviously is intrinsic to both Instant.now().toEpochMilli() and System.currentTimeMillis()).
If there is a slight performance difference between the two, I have a hard time imagining the situation where this will matter.
Take the option that you find more readable and less surprising in your context.
Similar questions
JSR 310 :: System.currentTimeMillis() vs Instant.toEpochMilli() :: TimeZone
Java current time different values in api
As per my understanding Instant.now().toEpochMilli() is better as Java-8 onward usage of Instant has been recommended.
Also, it works based on timeline and instant represents a specific moment on that timeline.
In case of java.lang.System.currentTimeMillis() method it returns the current time in milliseconds. The granularity of the value depends on the underlying operating system and may be larger.
Hence, to be consistent altogether use Instant.
I want to add that System.nanoTime() is less about precision but more about accuracy.
System.currentTimeMillis() is based on the system clock, which is, most of the time, based on a quartz clock inside a computer. It is not accurate and it drifts. (VM is even worse since you don't have a physical clock and have to sync with the host) When your computer syncs this quartz clock with a global clock, you might even observe your clock jumps backward/forward because your local clock is too fast or slow.
On the other hand, System.nanoTime() is based on a monotonic clock. This clock has nothing to do with the actual time we humans speak. It only moves forward at a constant pace. It does not drift like the quartz clock and there is no sync required. This is why it is perfect for measuring elapses.
For what it's worth, I've done a quick non-ideal performance test comparing the two methods.
On my system (Ubuntu 20.04, OpenJDK 17.0.4), running System.currentTimeMillis ten million times takes cca 230ms while running Instant.now().toEpochMilli() ten million times takes cca 370ms.
import java.time.Instant;
public class A {
public static void main(String[] args) {
long a = 0;
long start = System.currentTimeMillis();
for (int i = 0; i < 10_000_000; i++) {
//a += Instant.now().toEpochMilli();
a += System.currentTimeMillis();
}
System.out.println(a);
System.out.println(System.currentTimeMillis() - start);
}
}
I want to get a difference in hours between a current time in a specific timezone and UTC time. I tried this:
LocalTime time = LocalTime.now();
System.out.println(time); //21:05:42:764
LocalTime utcTime = LocalTime.now(ZoneId.of("UTC"));
System.out.println(utcTime); //18:05:42:769
System.out.println(Duration.between(utcTime, time).getSeconds()/3600); //2
System.out.println(Duration.between(time, utcTime).getSeconds()/3600); //-3
Why is the difference between the last two results and are there better ways to do it? I need to get the number 3.
Why is the difference between the last two results
The reason that you're getting different results for the two computed durations is a combination of the fact that there is some tiny amount of time elapsed between the two recordings and the fact that the duration start time is included in the range but the duration end time is not.
Consider these times instead: 6:00:00:001 vs 8:00:00:000. Here it is very obvious that we're only exactly one millisecond off of two hours, but when we think about seconds we're either going to get 7199 or -7200. When we then do integer math (i.e. divide by 3600), we're going to get 1 or -2.
If it weren't for the one extra millisecond on the first timestamp, the absolute value of the two would be identical.
Duration is the wrong class. There is zero duration between "now" in one time zone and "now" in another. For a fun but memorable way to think about this, see here.
You appear to be seeking to know the current offset from UTC for a given time zone. You can use the ZonedDateTime class for that:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
ZoneOffset offset = zdt.getOffset();
int offsetMinutes = offset.getTotalSeconds() / 60;
double offsetHours = ((double) offsetMinutes) / 60;
System.out.println(offsetHours); // 5.5
You could also just use ZonedDateTime.now() on the first line, if you want to use the computer's current time zone.
With regard to LocalTime - that is just the time portion (hours, minutes, seconds, and smaller). Since there is no date associated, you can't necessarily determine which time zone offset it belongs to. There is more than one date that "today" going on at any given moment. Time zone offsets range from UTC-12 to UTC+14, so there are indeed values where the same time of day is happening on two different dates somewhere on the planet.
As an example, 08:00:00 in Hawaii (Pacific/Honolulu) on 2019-01-01 is also 08:00:00 in Kiribati (Pacific/Kiritimati), but on 2019-01-02 - the following date! (Reference here.) Thus, if you had a LocalTime object with 08:00:00 and it was 08:00:00 in one of those two zones, you'd not be able to tell which one it was, or what the corresponding UTC offset should be.
Also, keep in mind that time zone offsets are not limited to whole hours. There are present-day time zones with half-hour and 45-minute offset. Historically, there have been others.
Lastly, keep in mind that an offset is not necessarily enough to identify a time zone. Many time zones share offsets at some points in time, but differ in others. See "Time Zone != Offset" in the timezone tag wiki.
Oh, and about your results getting 2 in one direction and -3 in the other - this is a rounding error due to your integer division. If you print out the seconds value, you'll notice they are one second apart (10799, vs -10800). Dig closer and you'll find that "now" included fractional seconds that were truncated with the getSeconds call. (You called .now() twice, so they were at slightly different times.)
Is TimeZone.getDSTSavings() in java returns always positive value or Negative values also?
I have tried this way
long millisecondsForGivenDateTime = 0l;
if (TimeZone.getTimeZone(strTZID).inDaylightTime(
new Date(millisecondsForGivenDateTime))) {
millisecondsForGivenDateTime = (millisecondsForGivenDateTime + TimeZone
.getTimeZone(strTZID).getDSTSavings());
}
here strTZID is timezone id dynamically passed to this function and millisecondsForGivenDateTime contains the dynamic value.
I am always getting 3600000 or 0 won't this function return -3600000?
In theory it could return a negative value - if you were using a TimeZone subclass where daylight saving time caused clocks to go back rather than forward.
I very much doubt you'll see that in the wild, although I have seen something similar in the Windows time zone database to get around the fact that Windows couldn't cope with time zones changing their standard UTC offset... if a zone went from UTC+5 to UTC+6 (as standard time) for example - and stopped observing DST - the zone data indicated that "DST" was actually -1 hour, and just inverted when it was in effect from what humans would expect. I've seen this with the Russian time zone, although I believe the data is cleaner now.
The desktop JRE prevents you from constructing a SimpleTimeZone with negative DST savings, but I don't know whether the same (undocumented) limitation is present in Android. You could always create your own subclass of TimeZone which did return a negative offset though.
This class returns 3600000 (1 hour) for time zones that use daylight savings time and 0 for timezones that do not, leaving it to subclasses to override this method for other daylight savings offsets.
If it were returning both positive and negative values, that would cause a two hour difference between the seasons.
When I use System.currentTimeMillis() to measure the time, is it safe?
E.g. When a time-shift happens (summer->winter time) will this produce an error?
No, System.currentTimeMillis() returns the number of elapsed milliseconds since the Unix epoch (midnight at the start of January 1st 1970, UTC). This does not depend on your local time zone at all.
In other words, if you call it once per second, it will always increase by about 1000 (the "about" is only due to clock accuracy and the impossibility of the calls being exactly 1 second apart). It doesn't matter if your local time zone changes its offset from UTC, or if you even change your whole time zone - that will be irrelevant.
In theory, leap seconds make all of this trickier - but in practice most applications can get away with notionally sticking their fingers in their ears and saying "I'm not at home to Mr Leap Second."
System.currentTimeMillis() will return the milliseconds since epoch (1/1/1970 00:00:00). How those are interpreted is a completely different story (and summer/winter time as well as timezone belong to the interpretation part). So yes, it would be save.
This question already has answers here:
How to check if 2 dates are on the same day in Java
(4 answers)
Closed 8 years ago.
I have two calendar objects, they seems to contain same dates but the compareTo() method is returning -1 as result, Can any one explain the reason behind this.
On debugging the two Calendar objects, the result is shown as :
2014-06-01T00:00:00.000Z
for both calendar objects but the compareTo() is returning -1. Even the long time in millis for both dates are different.
Well, have a look at the Calendar code (this is from JDK 1.7.0-13):
public int compareTo(Calendar anotherCalendar) {
return compareTo(getMillisOf(anotherCalendar));
}
private int compareTo(long t) {
long thisTime = getMillisOf(this);
return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
}
It should be obvious that if the two Calendar's have different millis, then they're different as per the second method.
In any case, the millis in your example should not both represent 2014-06-01T00:00:00.000Z so there's another problem in your code. Try this:
Timestamp ts1 = new Timestamp( 1401561000000L );
Timestamp ts2 = new Timestamp( 1401595200000L );
System.err.println( ts1 );
System.err.println( ts2 );
Outputs:
2014-05-31 20:30:00.0
2014-06-01 06:00:00.0
Cheers,
The milliseconds number is the "offical" time in Java. However, for a variety or reasons, there are numbers with the same date/time which have different numbers of milliseconds. Then normal reason is clock adjustments. E.g. Sometimes you have to add a second or two to account for irregularities in the earth's orbit. The other big source is when regions were first brought into the UTC, then some time zones moved hours.
THere is also the common source for these things: DST.
This will happen twice a year when you move to daylight saving time, on the one hand there are date/times which do not exists, as they were "skipped", and there are other times which happened twice, as the clock gets reset at midnight, so 11pm-midnight happens twice on the same day.
If you want to just compare the minutes and ignore the milliseconds or seconds do this:
You need to use
cal.set(Calendar.MILLISECOND, 0);
and possibly as well
cal.set(Calendar.SECOND, 0);
if you just need the minutes to match.
Quick explanation of what is going on:
The JavaDoc for Calendar states:
Compares the time values (millisecond offsets from the Epoch)
represented by two Calendar objects.
So you acknowledge that ".. long time in millis for both dates are different .."
#JonSkeet says in this question:
Calendar.setTime takes a java.util.Date, which is just a wrapper
around a long indicating the number of milliseconds since midnight Jan
1st 1970, UTC. It's not "in the format MM/dd/yyy" - that's a string
representation, not a java.util.Date. If it happens to print something
out in the format MM/dd/yyyy, that's just what Date.toString is doing
for you - it's not inherently part of the format.
This should answer your question about what is going on.
Note: java.util.Date has the same problem.
PS. A lot of people say use Joda Time, which I have heard is going to be in Java 8, but I have not personally tried it. If you are going to be using a lot of date code, I'd recommend you use it.
I invoked compareTo on Date instead of Calendar and got the correct result. It might be because of the fact that Calendar stores Timezone information but Date object does not.
Thanks