I need to determine if a time stamp is an exact hour (i.e. it represents a time with no minutes, seconds or milliseconds components) - using primitives only. The code is called several hundred times per second and I don't want the overhead of a Calendar or other object.
I've tried this but rounding errors cause the comparison to fail.
float hours = (time / 3600000f);
boolean isExactHour = hours == (int)hours;
For example, if time = 1373763600470, hours = 381601.03125. That time stamp represents 01:00:00:000 GMT today and hours should be 381601.
Any ideas for a quick and simple way to do this? Thanks!
[EDIT]
It seems that this is more complex than at first sight (when is it not? :)
For clarity, I don't care about time zones, nor leap seconds. The time stamp is generated by a method which returns the previous midnight - i.e. 13 July 2013 00:00:00:000 for today. I am then calculating, for any time stamp in an array of longs which is always this initial time stamp plus/minus an exact multiple of 5 minutes. My aim to to determine if a given stamp is "top of the hour". I might have edge cases where the multiple of 5 minutes overlaps a year end but I can live with those.
(time % 36000000) == 0
Surely this is obvious?
EDIT
To get accuracy w.r.t. leap seconds, assuming a lookup table of leap seconds indexed by year since (say) 1970, something like:
((time-leapSeconds[(int)(time/(1000*60*60*24*365.2425))-1970]*1000) % 3600000) == 0
Programmers needing this level of accuracy should also see all of Einar's comments below.
Related
I have two times in hours and minutes.
time[0]: hour1
time[1]: minutes1
time[2]: hour2
time[3]: minutes2
I've created this formula to calculate the difference in time in minutes:
((time[2] % 12 - time[0] % 12) * 60) + (time[3] - time[1])
I was wondering if there are any edge cases to this. In addition, what is the paradigm you would follow to create this formula (although it is very basic)?
You could express your times with the Date class instead, then calculate the difference and then express it in the time unit of your choice.
With this method, you will avoid a lot of tricky cases (difference between two times on two different days, time change, etc.).
I recommend you the reading of this post and this post but there are many answers to this same exact question on StackOverflow ;)
Note: before using Date, have a look to this excellent post: What's wrong with Java Date & Time API?
Your code assumes days are 24 hours long. Not all days are 24-hours long. Anomalies such as Daylight Saving Time (DST) mean days vary in length.
Also, we have classes already built for this. No need to roll your own. The LocalTime class represents a time-of-day without a date and without a time zone. A Duration represents a span of time not attached to the timeline.
LocalTime start = LocalTime.of( 8 , 0 ) ;
LocalTime stop = LocalTime.of( 14 , 0 ) ;
Duration d = Duration.between( start , stop );
long minutes = d.toMinutes() ; // Entire duration as a total number of minutes.
That code too pretends that days are 24 hours long.
For realistic spans of time, use the ZonedDateTime class to include a date and time zone along with your time-of-day.
I have two longs representing time since the epoch. They both have the same timezone. I want to find the difference in seconds between these two times, respecting day light savings.
(def a (java.util.Date. 1259568796000)) ;; Before Day Light Savings
(def b (java.util.Date. 1255147200000)) ;; After Day Light Savings
Where 'a' is 2009-11-30T08:13:16.000-00:00
and
Where 'b' is 2009-10-10T04:00:00.000-00:00
Using JodaTime, I can make an Interval out of these two times, turn them into a Duration, and get the StandardSeconds.
(.getStandardSeconds (.toDuration (Interval. a b)))
This doesn't work though, because the docs for Period indicate that Duration will mess up Day Light Savings:
When this time period is added to an instant, the effect is of adding
each field in turn. As a result, this takes into account daylight
savings time. Adding a time period of 1 day to the day before daylight
savings starts will only add 23 hours rather than 24 to ensure that
the time remains the same. If this is not the behaviour you want, then
see Duration.
How can I accomplish this task?
The long in Java represents a certain point in time (milliseconds since midnight on 1.1.1970, ignoring leap seconds). They don't carry a time zone and do not switch with daylight savings time, it is always expressed in UTC. To find the difference in seconds between two such timepoints you can use
(secondTime - firstTime) / 1000
The two times you have given are expressed in GMT, i.e.
1259568796000 = 2009-11-30T08:13:16.000-00:00 GMT
1255147200000 = 2009-10-10T04:00:00.000-00:00 GMT
And GMT does not switch to daylight savings time either. Maybe you were confused by that.
The java.util.Calendar class has support for daylight savings. Perhaps run your dates through that first? It should do the normalization for you. Check out this other post.
I want to calculate the number of days from the "beginning of time" to a current date. This could be easily achieved with a simple calculation (timestamp / 24 / 60 / 60 / 1000 = daysFromBeginningOfTime) but the twist is that i need to be aware of time zones as well. The timestamp is the same everywhere in the world but when you parse it with the proper time zone then it reflects the differences between locations so using just the timestamp doesn't work and i don't want to handle all the time zone transitions myself.
Example:
if it's 23:30 in London and the day number is 18843 then in Amsterdam it's 0:30 and the day number should be 18844.
I looked at joda.time but didn't really find what i was looking for.
Anyone have any ideas?
The problem appears due to a wrong initial assumption, I think.
The argument the OP makes in his example is not correct. No matter what the clock shows in London or Amsterdam, the time difference to the start of the epoch is - at every point of time - independent of where you are in the world.
Hence, the solution is to parse a given input date to an UTC timestamp and proceed as before.
(Ignoring the point that zero is not "the beginning of time" ... and that the actual time point for the beginning of time is probably unknowable ...)
Here's how to calculate the number of days since "the local-time UNIX epoch in a given timezone"1.
Get hold of the object that represents the local timezone.
Get the timezone's offset from the object
Convert it to milliseconds and add it to the current UTC time.
Calculate the day number as before.
1 - ... whatever that means.
There is a lot of similar topics but I couldn't find something similar then my problem. I've found only how to calculate if for example second time is greater then first time, like:
22:00
23:00
The result is easy to get. Just subtract second time with first using Date API. Difference is in milliseconds and you can easily convert them in seconds/minutes..
What I want to know, how to get difference between time in first day and time in second day, for example:
22:25
06:30
Difference should be 8 hours and 5 minutes.
Or another example
19:00
00:00
Difference should be 5 hours.
How to calculate time in this way? Any help is appreciated.
Convert your date and time to TimeStamp (It's just the long representation of a date in milliseconds since Jan. 1, 1970.), then calculate difference, and transferred from milliseconds to hours.
Also check this
Use Calendar class. Set your day, hour and minutes and finally subtract those dates (in milliseconds) and you will convert result in hour, minutes and seconds.
I need a fast implementation of a "Date jump" algorithm that is to be included in an event management system.
An event is triggered and sets a date (in a synchronized method) to the next 10th minute.
For instance
Event occurs at "2010-01-05 13:10:12" and sets the
next date to be "2010-01-05 13:20:00"
and if an event occurs exactly (supposedly) at a 10th minute, the next one must be set
Event occurs at "2010-01-05 13:30:00" and sets the
next date to be "2010-01-05 13:40:00"
(unlikely since the date goes down to the 1/1000th of a second, but just in case...).
My first idea would be to get the current Date() and work directly with the ms from the getTime() method, via integer (long) division, like ((time / 10mn)+1)*10mn.
Since it has to be fast, and also reliable, I thought I'll ask my fellow OSers prior to the implementation.
You can use / adapt my answer to a very similar question:
How to round time to the nearest quarter in java?
Something like this:
int unroundedMinutes = calendar.get(Calendar.MINUTE);
int mod = unroundedMinutes % 10;
calendar.add(Calendar.MINUTE, mod == 0 ? 10 : 10 - mod);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Your approach with the epoch time in ms will not work for arbitrary time zones, since some time zones have a N*15 minutes offset from GMT. Within these time zones, your code would move the interval 5-14 to 15, 15-24 to 25 and so on.
Have you actually tested the performance when manipulating the appropriate fields in the GregorianCalendar class and concluded that the performance is insufficient, or are you trying to reinvent a wheel just for the fun of it?