Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a timestamp is within working hours?

Tags:

java

timestamp

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.

like image 711
NightDog Avatar asked May 28 '11 17:05

NightDog


2 Answers

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.

like image 111
Joshua Martell Avatar answered Nov 11 '22 04:11

Joshua Martell


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.

like image 32
Wolfgang Avatar answered Nov 11 '22 05:11

Wolfgang