Difference between minutes - java

Say I have 2 strings in the following format:
"09/21 10:06AM"
"09/21 10:10AM"
How do I find the time difference between these strings, stored as an int? This has to be robust enough to handle situations like 10:59AM and 11:02AM (odd number of minutes in between), 11:59AM and 12:03PM (AM to PM switch) etc. No need to worry about seconds.
Thanks!

I would suggest:
Use Joda Time instead of the built-in API; it's much nicer.
Parse into LocalDateTime values
Find the difference between them with:
Minutes period = Minutes.minutesBetween(first, second);
int minutes = period.getMinutes();

DateFormat.Parse
Calculate difference between dates.

Parse the strings to Date objects and get the difference between them in milliseconds. Then convert those milliseconds to minutes (divide by 60000 and take the ceiling of the result).

If there is a switch to daylight savings the difference can be an hour more on one day than another.
It best to use a library which does this already. JodaTime is best, but SimpleDateFormat and Date will probably do what you need.

Convert the 2 Strings to Dates.
Subtract one from the other.
Multiply the result by 1440 (Number of minutes in a day).
Round the result to an Integer.
Let me know if it works :)

Related

Java - Store amount of time (not interval)

I work with an spring4 webapp that needs the logic of storing and calculating an amount of time(hours and minutes), but it isn't an interval since the amount is inserted by user or retrieved by third part app with the HH:MM format.
By now it's done with Float values which I want to change because in float the minutes are in 100 base, and not in 60 base as it's correct.
I've tried the java.time.LocalTime but it doesn't work since it's not acceptable more than 24 hrs.
I think there may be a cleaner way to deal with it.
Thanks in advance
-----EDIT
This webapp calculate overtime work. The user inputs the amount of hours the employee have worked off contractual time.
At the moment it is mapped as a float field, which is converted an calculated as below:
float hours = //Conversion of the HH:MM string input to HH.MM float within the framework
valueToPay = hours * employee.getHourSalary();
This way isn't right because the minutes are not being calculated correctly. I could convert the entire time to amount of minutes, but I'm searching for a cleaner way, since the java.time API offers a lot.
LocalTime is for time of the day.
If you need a ducation, you have java.time.Duration. For example, a duration of 30 hours (which would not fit in a LocalTime):
Duration thirtyHours = Duration.ofHours(30);
use org.joda.time.Duration
from javadoc:
An immutable duration specifying a length of time in milliseconds.
A duration is defined by a fixed number of milliseconds. There is no concept of fields, such as days or seconds, as these fields can vary in length. A duration may be converted to a Period to obtain field values. This conversion will typically cause a loss of precision however.
Duration is thread-safe and immutable.

difference in seconds between two dates using joda time?

Suppose there are two dates A(start time) & B(end time). A & B could be the time on the same day or even different day. My task is to show difference in seconds. Date format which i am using is
Date Format :: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
For e.g.
start date :: "2011-11-16T14:09:23.000+00:00"
end date :: "2011-11-17T05:09:23.000+00:00"
Help is appreciated.
Use the Seconds class:
DateTime now = DateTime.now();
DateTime dateTime = now.plusMinutes(10);
Seconds seconds = Seconds.secondsBetween(now, dateTime);
System.out.println(seconds.getSeconds());
This piece of code prints out 600. I think this is what you need.
As further advice, explore the documentation of joda-time. It's pretty good, and most things are very easy to discover.
In case you need some help with the parsing of dates (It's in the docs, really), check out the related questions, like this:
Parsing date with Joda with time zone
The answer of #pcalcao will be best in most cases. Be aware that seconds will be rounded to an integer.
If you are interested in sub-seconds accuracy just substract the milliseconds:
double seconds = (now.getMillis() - dateTime.getMillis()) / 1000d;

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).

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.

Categories