I am storing two DateTimes (Joda) in an object and then I get a Period from the object by new Period(dateTime1, dateTime2).
I then want to add all the periods from different objects together.
I am both adding all the periods together in a variable and summing up some periods in smaller periods stored in a HashMap<long, Period>.
The result and issue is this.
The first period gets "2 hours and 30 minutes" with a PeriodFormat.getDefault().print(p) (the values are the same if i concatenate getHours and getMinutes).
The second value "5 hours and 52 minutes". So far so good.
But when I do it with the 3rd and 4th, the minutes stop converting to hours.
"5 hours and 103 minutes"
"8 hours and 132 minutes"
It should be 10h and 12m, but as you can see. That's not what I am getting. What is the issue? How can Period just forget to do the conversion? I don't have any problems with the selected sums, yet.
code: (with variable names changed)
mainSum= new Period();
tasksSum= new HashMap<Long, Period>();
for(Entry entry: entries){
long main_id= entry.getMain_id();
long task_id = entry.getTask_id();
Period entryPeriod = entry.getPeriod();
if(main_id == mainStuff.getId()){
mainSum = entryPeriod.plus(mainSum);
Timber.d("mainSum: " + PeriodFormat.getDefault().print(mainSum));
Timber.d("sum of workplace: " + mainSum.getHours() + " : " + mainSum.getMinutes());
Period taskPeriod = tasksPeriodSums.remove(task_id);
if(taskPeriod == null){
tasksPeriodSums.put(task_id, entryPeriod);
} else {
tasksPeriodSums.put(task_id, taskPeriod.plus(entryPeriod));
}
}
}
Please help, thank you :)
This is documented behaviour, check out the Javadoc for the plus(Period) function:
/**
* Returns a new period with the specified period added.
* <p>
* Each field of the period is added separately. Thus a period of
* 2 hours 30 minutes plus 3 hours 40 minutes will produce a result
* of 5 hours 70 minutes - see {#link #normalizedStandard()}.
* <p>
...
Drilling down into the Javadoc of the normalizedStandard(..) function itself, we see what's the tradeoff:
/**
* Normalizes this period using standard rules, assuming a 12 month year,
* 7 day week, 24 hour day, 60 minute hour and 60 second minute,
*
...
* However to achieve this it makes the assumption that all years are
* 12 months, all weeks are 7 days, all days are 24 hours,
* all hours are 60 minutes and all minutes are 60 seconds. This is not
* true when daylight savings time is considered, and may also not be true
* for some chronologies.
...
Related
This question already has answers here:
integer giving negative values in java in multiplication using positive numbers [duplicate]
(4 answers)
Closed 3 years ago.
I know this has been asked on here many times previously, but I'm haven't been able to find anything specific to my case. I'm trying to find the difference between the current datetime and a previous datetime, each with the format yyyy-MM-dd HH:mm:ss.s. Based on the answer given here, I've come up with the following code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s");
String earliestRunTime = "2017-12-16 01:30:08.0";
Date currentDate = new Date();
log.info("Current Date: {}", format.format(currentDate));
try {
Date earliestDate = format.parse(earliestRunTime);
long diff = currentDate.getTime() - earliestDate.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000) % 30;
long diffMonths = diff / (30 * 24 * 60 * 60 * 1000) % 12;
long diffYears = diff / (12 * 30 * 24 * 60 * 60 * 1000);
return String.format("%s years, %s months, %s days, %s hours, %s minutes, %s seconds",
diffYears, diffMonths, diffDays, diffHours, diffMinutes, diffSeconds);
}
catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
When I run the code, the JSON returns the following result:
lifetime: "41 years, -1 months, 14 days, 9 hours, 42 minutes, 37 seconds"
I have two questions here:
Where am I going wrong in my calculations 41 years and a negative number?
Is there a better way for me to do this? My current setup does not consider leap years or a 365 day year, and I need to take these into account.
Where am I going wrong in my calculations 41 years and a negative number?
Because the denominator will overflow. You need to use Long:
long diffMonths = diff / (30 * 24 * 60 * 60 * 1000L) % 12; //Notice the L at the end
long diffYears = diff / (12 * 30 * 24 * 60 * 60 * 1000L); //Notice the L at the end
Also note that 12 * 30 is a really bad approximation of the number of days in a year.
Is there a better way for me to do this?
Yes. Use Duration api from Java 8. https://www.mkyong.com/java8/java-8-period-and-duration-examples/
It's hard to give precise answer, because the question is a bit vague. For example - If one of the year was a leap year and you were comparing dates 2020/03/28 and 2021/03/28, what should be the result? 1 year or 1 years, 1 days? (2020 is a leap year so after 03/28, there's also 03/29)
Where am I going wrong in my calculations 41 years and a negative number?
Apart from using the notoriously troublesome and long outdated SimpleDateFormat class and the just as outdated Date there are the following bugs in your code:
You are parsing 08.0 as 8 seconds 0 seconds. On my JDK-11 SimpleDateFormat opts for the 0 seconds and discards the 8 seconds that I think are correct. SimpleDateFormat cannot parse one decimal on the seconds (only exactly three decimals), so the solution to this bug is discarding SimpleDateFormat altogether.
As others have said you have an int overflow in your multiplications. For example, 30 * 24 * 60 * 60 * 1000 should give 2 592 000 000, but since an int cannot hold this number, you get -1 702 967 296 instead. Since this is a negative number, the following division gives you a negative number of months.
As Solomon Slow pointed out in a comment, a month may be 28, 29, 30 or 31 days. When setting all months to 30 days you risk incorrect numbers of days and months and in the end also years. When I ran your code today, the correct answer would have been 1 year, 4 months, 13 days, but I got 19 days instead, 6 days too much.
You are not taking summer time (DST) and other time anomalies into account. These may cause a day to be for example 23 or 25 hours, giving an error.
Or to sum up: Your error was that you tried to do the calculation “by hand”. Date and time math is too complex and error-prone to do this. You should always leave it to well-proven library classes instead.
Is there a better way for me to do this? My current setup does not consider leap years or a 365 day year, and I need to take these into
account.
Yes, there is a much better way. The best way may be to use the PeriodDuration class from the ThreeTen Extra project, see the link below. I am not going to install that library in my computer right now, so I will just show the good and modern solution using built-in classes:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.S");
LocalDateTime currentDateTime = LocalDateTime.now(ZoneId.of("Australia/Sydney"));
String earliestRunTime = "2017-12-16 01:30:08.0";
LocalDateTime earliestDateTime = LocalDateTime.parse(earliestRunTime, dtf);
// We want to find a period (years, months, days) and a duration (hours, minutes, seconds).
// To do that we cut at the greatest possible whole number of days
// and then measure the period before the cut and the duration after it.
LocalDateTime cut = earliestDateTime.plusDays(
ChronoUnit.DAYS.between(earliestDateTime, currentDateTime));
Period p = Period.between(earliestDateTime.toLocalDate(), cut.toLocalDate());
Duration d = Duration.between(cut, currentDateTime);
String result = String.format("%s years, %s months, %s days, %s hours, %s minutes, %s seconds",
p.getYears(), p.getMonths(), p.getDays(),
d.toHours(), d.toMinutesPart(), d.toSecondsPart());
System.out.println(result);
When I ran the code just now I got:
1 years, 4 months, 13 days, 19 hours, 26 minutes, 7 seconds
In java.time, the modern Java date and time API, a Period is an amount of years, months and days, and a Duration is an amount of hours, minutes, seconds and fraction of second (down to nanoseconds). Since you wanted both, I am using both classes.
The toXxxPart methods of Duration I am using were introduced in Java 9. If you are using Java 8 (or the ThreeTen Backport) printing the minutes and seconds is a little bit more complicated. Search for java format duration or similar to learn how.
I am still not taking summer time into account. To do that we would need to know the time zone of the earliest run time string and then use ZonedDateTime instead of LocalDateTime. The code would otherwise be very similar.
Links
ThreeTen Extra
Documentation of PeriodDuration
Oracle Tutorial: Date Time explaining how to use java.time
Using the same approach you did, you need to explicitly identify the denominator as long values. Currently, it assumes them to be integers, which causes a numeric overflow - meaning the value computed is too large for a integer. This would explain why you get negative/arbitrary values. Fix is simple:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s");
String earliestRunTime = "2017-12-16 01:30:08.0";
Date currentDate = new Date();
log.info("Current Date: {}" + format.format(currentDate));
try {
Date earliestDate = format.parse(earliestRunTime);
long diff = currentDate.getTime() - earliestDate.getTime();
long diffSeconds = diff / 1000L % 60L;
long diffMinutes = diff / (60L * 1000L) % 60L;
long diffHours = diff / (60L * 60L * 1000L) % 24L;
long diffDays = diff / (24L * 60L * 60L * 1000L) % 30L;
long diffMonths = diff / (30L * 24L * 60L * 60L * 1000L) % 12L;
long diffYears = diff / (12L * 30L * 24L * 60L * 60L * 1000L);
return String.format("%s years, %s months, %s days, %s hours, %s minutes, %s seconds",
diffYears, diffMonths, diffDays, diffHours, diffMinutes, diffSeconds);
}
catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
I have an app where i need to check if travel is in duration between 4 hours and 30 hours, I store it as a strings "04:00" and "30:00", then i try to parse it using LocalTime.parse(), "04:00" is parsed successfully but "30:00" gets an error for invalid format, what could be best way to parse duration hours from a string ?
First of all, you're storing it somehow wrong. I suggest to store it in way Duration.parse can handle it, in standard ISO 8601 format.
Examples:
"PT20.345S" -- parses as "20.345 seconds"
"PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
"PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
"P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
"P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
"P-6H3M" -- parses as "-6 hours and +3 minutes"
"-P6H3M" -- parses as "-6 hours and -3 minutes"
"-P-6H+3M" -- parses as "+6 hours and -3 minutes"
So then you can just do:
Duration dur30H = Duration.parse("PT30H"); // 30h
Duration dur4H = Duration.parse("PT4H"); // 4h
Duration travelTime = Duration.parse("P1D"); // 1D
boolean result = travelTime.compareTo(dur30H) <= 0 && travelTime.compareTo(dur4H) >= 0; // true
I am looking for a neat solution to get the time units in Java 7 ( or using Joda date time)
Like, to 65 minutes, it should say 1 hour 5 minutes
To 30 minutes, it should just say 30 minutes
Thanks.
You can use joda time's normalizedStandard to print your output too.
Per the doc,
Normalizes this period using standard rules, assuming a 12 month year,
7 day week, 24 hour day, 60 minute hour and 60 second minute.
An example for 65 minutes would be:
System.out.println(PeriodFormat.getDefault().print(Period.hours(0).plusMinutes(65).plusSeconds(0).normalizedStandard()));
Output:
1 hour and 5 minutes
Short answer, use org.joda.time.Period.
For example, a general purpose solution might be to have a method that takes the number of milliseconds and returns a String of the form:
X hours, X minutes, X seconds, X milliseconds
public class DateTimeUtils {
public static String toNicePeriodValue(Period period) {
return period.getHours() + "hours " +
period.getMinutes() + "minutes " +
period.getSeconds() + "seconds " +
period.getMillis() + "milliseconds";
}
}
An easy way to create a Period object is like this:
public String nicePeriodValueFromMillis(long timeInMillis) {
Period period = new Period(timeInMillis);
String ret = DateTimeUtils.toNicePeriodValue(period);
return ret;
}
And invoke it like this:
long timeInMillis = /* obtain somehow */
String nicePeriodValue = nicePeriodValue(timeInMillis);
System.out.println("Nice Period Value: " + nicePeriodValue);
This is not, of course, a complete solution, but it should get you started.
If your input is always minutes use the modulus operator % 60 to find remaining minutes and / 60 to find hours.
I have simple question, I have the following function and there is argument on it that called cacheTime, How can I set it to 4 hours, should I set it to 4 * 3600000?
public static File getCache(String name, Context c, int cacheTime)
{
if (cacheTime <= 0)
return null;
File cache = new File(c.getCacheDir(), name);
long now = System.currentTimeMillis();
if (cache.exists() && (now - cache.lastModified() < cacheTime))
return cache;
return null;
}
miliseconds are 1/1000 of a second. So 4 hours would be 4 * 60 * 60 * 1000 = 14,400,000
For cache invalidation this is probably fine. That said, date math is often dangerous. When dealing with larger units of time than milliseconds one can easily get tripped up during daylight savings transitions, leap seconds and all the other stuff that Calendar is meant to take care of. In some cases that rare imprecision is acceptable, and in others it's not. Be careful when doing date math.
For determining human consumable times in larger units of time such as +1 days, use Calendar.roll().
Learn to use the handy TimeUnit enum so you can do things like so:
TimeUnit.Hours.toMillis(4)
And not rely on napkin math and magic numbers all over your code.
// 4 hours * 60 (min/hour) * 60 (sec/min) * 1000 (msec/sec)
getCache(name, c, 4 * 3600 * 1000);
4 * 1000 * 3600
There are 1000 milliseconds in a second and 3600 seconds in an hour.
I need to add 14 minutes and 59 seconds to an unknown time in an array. How do I do this? This is what I have so far:
Date duration = df.parse("0000-00-00 00:14:59");
arrayOpportunity[2] = arrayOpportunity[2] + duration;
The time is not being changed. Thanks!
I have done my research. I cant paste the entire code I have. But mainly I didnt want to make you read it all. Just looking for a simple answer of how to add two timestamps.
If you are talking about a java.sql.Timestamp, it has a method called setTime. java.util.Date has a setTime method as well for that sort of thing.
You could something like this:
static final Long duration = ((14 * 60) + 59) * 1000;
oldTimestamp.setTime(oldTimestamp.getTime() + duration);
If you want to add time in millis then you can just add
(((14 * 60) + 59) * 1000) <-- Mili second value of 14 m and 59 sec
If you just want to add times, I suggest using Joda Time.
The class LocalTime lets you add durations like this:
LocalTime timeSum = time.plusMinutes(14).plusSeconds(59);
Just add the appropriate number of milliseconds using #getTime() and #setTime():
timeStamp.setTime(timeStamp.getTime() + (((14 * 60) + 59)* 1000));
arrayOpportunity[2] = arrayOpportunity[2] + 14*60*1000 + 59*1000;
The Date object you have may work, but it doesn't really represent 14 minutes and 59 seconds, it just represents a particular time in calendar (eg. 14 minutes 59 after the epoch start which is 1st January 1970 00:14:59).