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.
Related
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.
We are using CXF in combination with Jackson (JacksonJaxbJsonProvider) to marshall domain objects into JSON. Everything is working good, with the exception that I cannot get dates to format the way I want them to. In short, what I want, is to output dates as seconds since epoch (also called unix time). This is partly doable with SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, but this gives me milliseconds, not seconds. As my dates don't have such high precision (and never will), I am wasting 4 bytes for every timestamp.
To my knowledge, the only way I can control the date format is by using setDateFormat() on ObjectMapper. This function accepts a DateFormat. However, it does not seem like a DateFormat can output seconds since epoch, only milliseconds.
Are there any other ways of doing this?
Given a any unix timestamp (i.e. 1306396801) which translates to 26.05.2011 08:00:01, how can I determine if this is within a given timeframe (i.e. 08:00:00 and 16:00:00)?
This needs to work for any day. I just want to know if this timestamp is within the given time-interval, on any future (or past) day, the date is unimportant. I don't care if it is on the 25th or 26th, as long as it is between 08:00 and 16:00.
I am on the lookout for a java solution, but any pseudo code that works will be ok, I'll just convert it.
My attempts so far has been converting it to a java Calendar, and reading out the hour/min/sec values and comparing those, but that just opened up a big can of worms. If the time interval I want it between is 16.30, I can't just check for tsHour > frameStartHour && tsMin > frameStartMin as this will discard any timestamps that got a minute part > 30.
Thank you for looking at this :)
To clarify.
I am only using and referring to UTC time, my timestamp is in UTC, and the range I want it within is in UTC.
I think I understand what you want. You want to test for any day, if it's between 8am and 4pm UTC. Take the timestamp mod 24*3600. This will give you the number of seconds elapsed in the day. Then you just compare that it's between 8*3600 and 16*3600. If you need to deal with timezones, things get more complicated.
Given your timestamp (in seconds) and the desired time zone, Jodatime gives you the hour which leads you to a simple integer range check.
new org.joda.time.DateTime(timestamp*1000L, zone).getHourOfDay()
With java.util.* its more difficult.
If I understood you correctly, you only need to normalize your dates to some common value. Create three instances of Calendar - one with your time, but day, month, and year set to zero, and two with start and end of your timeframe, other fields also zeroed. Then you can use Calendar.after() and Calendar.before() to see if the date is within the range.
Your unix timestamp is an absolute time. Your time frame is relative. You need some kind of time zone information in order to solve this problem. I just answered some of this for PostgreSQL a few minutes ago. Hopefully that article is of use.
Convert the beginning of your range to a unix timestamp, and the end of your range to a unix tmestamp, then it's a simple integer check.
What is the Objective-C equivalent of the Java TimeZone class?
The NSTimeZone class is the equivalent of the Java TimeZone class.
NSTimeZone, I believe. Can't say I've ever done any Objective-C myself, but it looks right...
Apple also has a (pretty short) article on using it.
It's quite likely that they won't be direct equivalents in every respect, of course... but if there's something you would use with Java's TimeZone which you can't figure out in NSTimeZone, ask about that specific call... and someone else can help you, I'm sure :)
EDIT: The purpose of a time zone class is to convert between local times in different time zones. For example, right now, it's 7.50pm for me - but it's 12.50pm for the person who I'm about to have a Skype call with. One option for representing dates and times is to always store them in UTC (which is sort of the "zero" of time zones) and then convert the UTC value into the "local" time for the user, e.g. for display purposes. That's not always the right option, but it's usually a good starting point.
At other times, you may have a local time and know person X's time zone - and want to convert it to person Y's time zone. It's usually easiest to do that by converting the local time to UTC (using X's time zone) and then to convert it back to local time using Y's time zone.
Time zones aren't nearly as straightforward as you might expect - mostly due to daylight savings. Oddities:
Local times which either don't exist, or occur twice, due to DST transitions
Time zones which change to DST at midnight, so that midnight doesn't always exist
Governments deciding to scrap (or introduce) DST at almost no notice
DST which isn't the normal "move an hour forwards". IIRC, Tibet was considering introducing DST of 1:15.
Historical changes to time zones
The list goes on.
NSTimeZone : http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/Reference/Reference.html
Regards.
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).