Equivalent of Erlang now() in Java - java

I am working on a project which requires timestamps for running threads. In Erlang, when we do now() we get something like
{1529,709564,578215} which represent {megaseconds, seconds, microseconds}
since epoch. So, for two processes spawned at the same time, I can get same microseconds value. Is there a way to replicate this function in Java?
I know about Date.getTime() which gives us the milliseconds since epoch time, but it does not serve the purpose since I cannot get a unique microsecond value from it after dividing by order of magnitude.
Any alternative?

System.out.println(Instant.now());
Output just now was:
2018-06-23T05:16:45.768006Z
On the Java 10 on my Mac it gave microsecond precision. Since Java 9 it will on many operating systems, maybe not all. Instant.now() returns an Instant. An Instant is implemented as seconds and nanoseconds since the epoch, and you can get out those individually if you want.

Related

Which one is recommended: Instant.now().toEpochMilli() or System.currentTimeMillis()

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);
}
}

Fetching UNIX epoch time in java

I was trying to fetch the current time in UTC in Java and came across this post: Getting "unixtime" in Java
I checked out that all solutions
new Date().getTime()
System.currentTimeMillis()
Instant.now().toEpochMillis()
return the same value. I wished to know if there is any difference between the three of them. If so then what?
There is no difference. This is just the result of the evolution of the date API over the years. There is now more than one way to do this.
As far as just getting epoch milliseconds, all three are fine. Things get more complicated as soon as formatting, calendars, timezones, durations and the like become involved.

subtracting time in Java

Hello I am trying to create a teacher utility to port over to android OS. However I am running into a little trouble. I would like to create a class called Period. This class would contain the start and end time of that period. ie. Period one starts at 7:45 and ends at 8:45. I would also like to have a method for time left in period. for example it is now 8:10 and there are 35 minutes left. I am able to get the current time from System.currentTimeMillis(). However I am having trouble trying to figure out the best way to store the start and end time of the periods. i have taken a look at the Calendar class in Java and it seems like time is always tied to a date as well as a time. This does not seem to make seance for my application since the end time of the period happens on multiple days and not just on one particular date. Any help understanding this would be a great help. Thanks all
If your goal is to be able to compare the start and end time of the period with the current time, then you need a way to compute the date and time of the period's bounds for today.
So get a Calendar instance for today, set its time to 7:45, and compare the time of the calendar with the current time (same for the upper bound, of course).
To represent each bound, you could simply use an int for the hours and a second int for the minutes.
Check out the JodaTime library. The DateTime object has what you want.
Take a look at JodaTime.
Specifically, Period: http://joda-time.sourceforge.net/key_period.html
Calendar is a king of wrapper around the class Date which has mostly deprecated functions. I've heard that the JodoTime API is great for comparing two timestamps (http://joda-time.sourceforge.net/).
One way to store the start and end time for the periods would be to instantiate an ArrayList of dates so you can compare any given time to the lesson periods.
From what I can tell, you should store the time as a number of seconds (optionally milliseconds) from last midnight. Thus, your period one, 7.45, starts at 45*60 (45 minutes * 60 seconds per minute) + 7*60*60 (7 hours times minutes times seconds!) = 2 700 + 25 200 = 27 900.
Do the same calculation for your end date, and as long as they begin and end on the same day, you can easily subtract the difference and thus get the interval in between. If they do not happen on the same date, then Java's time and date classes are both excellent and a must. These classes essentially work the same algorithm, but do not count the seconds from "last midnight", instead they count the amount of milliseconds from the UNIX epoch time (1 January 1970).

java display Windows UTC time

Windows stores FileTime internally as the number of 100-nanoseconds since 1.1.1601 UTC as a 64bit field, is it possible to get java to print out the current number? Just looking for an example as I can't find a way to do it. I would like to print the number out?
Any help woudl be greatful!
Thanks.
Approximately
long diff1601to1970 = 315532800 * 1000000000; // <-- diff in nanoseconds(1/1/1601 to 1/1/1970)
long currentFrom1970 = System.currentTimeMillis() * 1000000;
long currentFrom1601 = diff1601to1970 + currentFrom1970;
Java doesn't provide direct access to a raw file time, so if you ask for the lastModified time
someFile.lastModified();
You will get the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs
Not every platform tracks the "same" times in relation to a file, and how they track it internally is different. Part of Java's attempt to make a coherent platform out of the differing standards uses polymorphism to translate the platform specific times to the "java standard" under the covers.
Now to convert the millis returned to a java time:
java.util.Date date = new java.util.Date(millis);
From there you can use the standard i/o routines to display and format the date (DateFormat, etc.)
PS. 1/1/1601 was chosen as the epoch by COBOL initially and mimicked by Microsoft (and possibly others). The reason it was chosen is because it's the start of the 400 year Gregorian Calendar cycle at the time the operating system was released. Every 400 years, the pattern of leap years repeats itself.

Is java.util.Date using TimeZone?

I have 2 different computers, each with different TimeZone.
In one computer im printing System.currentTimeMillis(), and then prints the following command in both computers:
System.out.println(new Date(123456)); --> 123456 stands for the number came in the currentTimeMillis in computer #1.
The second print (though typed hardcoded) result in different prints, in both computers.
why is that?
How about some pedantic detail.
java.util.Date is timezone-independent. Says so right in the javadoc.
You want something with respect to a particular timezone? That's java.util.Calendar.
The tricky part? When you print this stuff (with java.text.DateFormat or a subclass), that involves a Calendar (which involves a timezone). See DateFormat.setTimeZone().
It sure looks (haven't checked the implementation) like java.util.Date.toString() goes through a DateFormat. So even our (mostly) timezone-independent class gets messed up w/ timezones.
Want to get that timezone stuff out of our pure zoneless Date objects? There's Date.toGMTString(). Or you can create your own SimpleDateFormatter and use setTimeZone() to control which zone is used yourself.
why is that?
Because something like "Oct 4th 2009, 14:20" is meaningless without knowing the timezone it refers to - which you can most likely see right now, because that's my time as I write this, and it probably differs by several hours from your time even though it's the same moment in time.
Computer timestamps are usually measured in UTC (basically the timezone of Greenwich, England), and the time zone has to be taken into account when formatting them into something human readable.
Because that milliseconds number is the number of milliseconds past 1/1/1970 UTC. If you then translate to a different timezone, the rendered time will be different.
e.g. 123456 may correspond to midday at Greenwich (UTC). But that will be a different time in New York.
To confirm this, use SimpleDateFormat with a time zone output, and/or change the timezone on the second computer to match the first.
javadoc explains this well,
System.currentTimeMillis()
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#toString().
Yes, it's using timezones. It should also print them out (the three characters before the year).

Categories