subtracting time in Java - 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).

Related

Java datetime offsets/timezones class?

Ok this seems like its been done or handled somewhere in a class but not sure.
Problem is I have an event object with a start and end time. Then there is a main "day" object its compared against. Problem now is everything is UTC so it all works fine. So when user changes event object to use say eastern time with offset -5 on the event, its being compared against this day object with UTC time so of course you can get overlaps against the main "day" object because its two different timezones being compared against each other. This is of course bogus. Right now code is comparing date getTimeMillis to see if the end date time in millis is less than Day objects 23:59 UTC time or if the objects start time is greater than the Day object start time of 00:01.
So... is there a class out there that I can simply pass in the two date time's in millis, time zone and get a yes/no answer that handles all these offsets?
I of course could do it all manually using the "afterDate" or "beforeDate" stuff but was hoping there is some fancy built already to handle it all already?

Define regular Time instances, get differences between them and current Time on Android

There're some objects that each one has certain constant times repeat daily (i.e. 12:30PM, 14, 16, 18 ...); I want to calculate differences between System current time and each time spot to find the closest one and show the difference too. I am facing 2 quandaries here:
How to define those clock detailed times that repeat daily, in Android Time class? I just found this format at reference time.set(4, 10, 2007)
Should I use compare(Time a, Time b) to find the closest Time to now? I'm not sure about the details though.
Have a look at the Joda date / time library, and specifically the LocalTime class, which represents a time of day that is not tied to a specific date. See http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalTime.html
You can use methods of the LocalTime class to convert to a time in the current day, and then compare.

Adding times, calculate total time

I try to calculate a List with times. But using LocalTime from Joda Time I can only get a 24 hours.
What is the right class to use to get e.g. 34hours 20minutes 14 seconds?
Thanks in advance
You may be look for Period:
A period in Joda-Time represents a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours. This differs from a duration in that it is inexact in terms of milliseconds. A period can only be resolved to an exact number of milliseconds by specifying the instant (including chronology and time zone) it is relative to.
If you are looking to add times, so you can tell how many hours/seconds... are in between, you would maybe be better off if you use plain miliseconds calculations, add all the miliseconds and then subsrtact the miliseconds from your first time, and there you are, you have the span in miliseconds...

How to determine if a timestamp is within working hours?

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.

Compare hours and minutes

I am developing an app based on date and time in java. In this app, my user is allowed to record an video only once per hour. so for this I am storing the previous time has used my app.
So when the user starts my app for the next time, I am comparing the time and if the time interval is more than one hour I must allow my user to record, else I should not allow. How to compare hours and minutes efficiently in java?
Get the system time with
long time = System.currentTimeMillis();
and compare the new time with the old one. One hour means a difference of 1000 * 60 * 60 milliseconds
From #Dalino answer, you may use TimeUnit enum class for time conversions.
long now = System.currentTimeMillis();
long lastVisit = ...; // in milliseconds
if(TimeUnit.MILLISECONDS.toHours(now - lastVisit) > 0) {
// allow
}
Why not just store the time when they exit (or whatever) and then on start up, read the time, add an hour to it, and compare with the current time?
You don't need to compare the actual hours and minutes - just the duration of time between then and now.
Personally I'd suggest using Joda Time for all Java date/time work, but in this case you could just use Date, and add an hour's-worth of milliseconds. Note that you should definitely store a UTC date/time instead of a local one, as otherwise daylight saving changes etc will mess things up.
I would use Joda Period: have a look here

Categories