Java how to calculate time differences - java

How can I calculate the time differences in 24 hour if the user input is 2255 and 2305 the output should be 10 minutes. I got an idea is to separate the input to 2 parts, 2 digits and 2 digits. the first 2 digits is the hour, times it to 60 to make it to minutes. Then plus it with the second 2 digits and then calculate the differences. I dont want use any Date Calendar data type or API to solve it. Thanks

String time1 = "2255";
String time2 = "2305";
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
difference is in millis you can convert it to any unit or you can use DurationFormatUtils from apache-commons to pretty format it.
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
apache commons has really nice utility functions, apache-commons (lang)

How to get first 2 digit without using String chartAt.
Highest two digits: number / 100
Lowest two digist: number % 100
But what would you do if user enter 3:05 or 3-05? I think it's problem of usability. Best solution is making UI definitely understandable for user. For example you can use separate fields for hours and minutes.

Related

Get 12 hours before and after current time

I'm having an issue working with time in Java. I don't really understand how to efficiently solve comparing the time of now and 12 hours before and after
I get a set of starting times for a show from an API and then compare that starting time with LocalTime.now(). It looks something like this:
SimpleDateFormat sdt = new SimpleDateFormat("HH:mm:ss");
String temp = sdt.format(Local.time(now));
LocalTime secondTime = LocalTime.parse(parts1[0]);
LocalTime firstTime = LocalTime.parse(temp);
int diff = (int) ((MINUTES.between(firstDay, secondDay) + 1440) % 1440);
if(diff <= 720){
return true;
}
Where my idea is that if the difference between the two times is smaller than 720 minutes (12 hours) I should get the correct output. And this works for the 12 hours before now. I thought I might need to swap the parameters of .between, to get the other side of the day. That counts it completely wrong (If the time now is 15:00:00 it would accept all the times until 22:00:00 the same day). Is this just a really bad way of comparing two times? Or is it just my math that lacks understanding of what I'm trying to do?
Thanks
Using the 'new' (not that new) Java 8 time API:
Instant now = Instant.now();
Instant hoursAfter = now.plus(12, ChronoUnit.HOURS);
Instant hoursBefore = now.minus(12, ChronoUnit.HOURS);
First, doing this kind of operations on java.time.LocalTime won't work! Or at least only if the time is "12:00:00" …
That is because you will have an over-/underflow when you add/substract 12 hours from any other time.
So your starting point should be to go for java.time.LocalDateTime (at least, although I would go for java.time.Instant). Now you can handle the over-/underflow, as you will get another day when adding or subtracting 12 hours.
How this works is shown in this anwswer: LocalDateTime allows nearly the same operations as Instant.

Java SimpleDateFormat.format() returns incorrect date when using miliseconds

I want to parse a date string from "2016-09-23T09:14:52.555000000" format to "23-SEP-2016" format.
Here is my code :
public class Tester {
public static void main(String[] args) {
System.out.println(displayDate("2016-09-23T09:14:52.555000000"));
System.out.println(displayDate("2016-09-28T11:56:24.552000000"));
System.out.println(displayDate("2016-09-23T09:29:12.507000000"));
System.out.println(displayDate("2016-09-26T14:55:02.702000000"));
System.out.println(displayDate("2016-09-26T09:50:24.880000000"));
System.out.println(displayDate("2016-09-26T15:20:49.397000000"));
System.out.println(displayDate("2016-09-26T15:21:21.559000000"));
}
public static String displayDate(String dateString) {
String formattedDateString = "NA";
if(dateString == null) {
return formattedDateString;
}
SimpleDateFormat oracleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.S");
SimpleDateFormat dateFormatToDisplay = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date date = oracleDateFormat.parse(dateString);
formattedDateString = dateFormatToDisplay.format(date).toUpperCase();
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDateString;
}
}
The problem is if I use this line
SimpleDateFormat oracleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.S");
The output is (incorrect date values) :
29-SEP-2016
04-OCT-2016
29-SEP-2016
04-OCT-2016
06-OCT-2016
01-OCT-2016
03-OCT-2016
Whereas If use this line
SimpleDateFormat oracleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss");
The output is (correct date values)
23-SEP-2016
28-SEP-2016
23-SEP-2016
26-SEP-2016
26-SEP-2016
26-SEP-2016
26-SEP-2016
I want to know why adding "S (Millisecond)" to the format string results in incorrect values.
Edit1 :
Even "yyyy-MM-dd'T'kk:mm:ss.SSS" returns incorrect values.
Edit2 :
I am using this code in Android App. It works on perfectly on emulator(API 23). For some devices it displays incorrect date. Can it be related to Java version?
TL;DR:
In Java, it's not a fraction of seconds, it's a number of milliseconds. Don't make it larger than 999.
Change your date format in Oracle to include FF3 for the fractions of seconds to yield milliseconds.
Explanation
In Java, the S, or rather SSS, in your date format stands for milliseconds, which are thousands of a second. There are only thousand milliseconds in one second.
In Oracle, the date format doesn't specify milliseconds, but fractions of a second.
FF [1..9]
Fractional seconds; no radix character is printed. Use the X format element to add the radix character. Use the numbers 1 to 9 after FF to specify the number of digits in the fractional second portion of the datetime value returned. If you do not specify a digit, then Oracle Database uses the precision specified for the datetime datatype or the datatype's default precision. Valid in timestamp and interval formats, but not in DATE formats.
In Java, if you need a third of a second, you can't get more precise than 333 milliseconds. In Oracle however, you could express it as 333333 microseconds, or perhaps even 333333333 nanoseconds.
Oracle lets you specify the number of decimal digits you want, but if you don't, you get as much as the precision for the type allows. In your case, that seems to be 9.
Then your date format in Java interprets that as a number of milliseconds. Millions and billions of them. These are added to the rest of your date. Since there are only 86,400,000 milliseconds in a day, anything over that is another day added to your date.
Example
Let's take a look at your first test case, 2016-09-23T09:14:52.555000000.
555000000 milliseconds = 555000 seconds &approx; 154 hours &approx; 6 days and 10 hours.
Adding 6 days and 10 hours to the rest of your date, which is 2016-09-23 09:14:52, should get you to about 2016-09-29 19:00 and a bit. Change your output format (dateFormatToDisplay) to include the hours and you'll see what's happening.
Fix
Your Java date format expects no more than 3 digits for the milliseconds. Specify the number of fractional digits in Oracle. FF uses the maximal precision available for the type, FF3 only outputs 3 fractional digits — milliseconds.
If you can't alter the date format used in Oracle, trim it down to three decimal digits in Java. Note that anything less than 3 digits should be padded with zeroes to a length of three digits; 34.12 is interpreted as 34 seconds and 12 milliseconds, while you might be looking for 120 milliseconds.
The mystery stays in the correct interpretation of the S specifier.
In SimpleDateFormat, on the Date and Time Patterns section, the definition for S states:
S Millisecond
Does it strikes you as peculiar in some way? No?! It took myself by surprise as well, so let me put it in a negative way:
Not fractional part of the seconds, but Milliseconds
Still don't get it? I mean literaly the count of milliseconds.
Like in:
SimpleDateFormat oracleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.S");
SimpleDateFormat dateFormatToDisplay =
new SimpleDateFormat("dd-MMM-yyyy--HH:mm:ss.SSS");
Date d=oracleDateFormat.parse("2016-09-23T09:14:52.1");
System.out.println(dateFormatToDisplay.format(d));
will result in... waaait for it... boom-tshhh...
"2016-09-23--09:14:52.001"
That's right folks! "And one millisecond" not "and one tenth of a second".
So, does it go the same way if we increase the number of digits after the dot? Sure it does.
d=oracleDateFormat.parse("2016-09-23T09:14:52.1000");
System.out.println(dateFormatToDisplay.format(d));
"2016-09-23--09:14:53.000"
So if you put in T09:14:53.555000000 you just added 555 millions of milliseconds to your base time or 555000 full seconds. Which means an extra 6 days, 10 hours and 11 minutes` over your base time.
It seems that when you add 'S' then parser adds all milliseconds eg "555000000" to date. When you do calculation (555000000 ms ~ 6,4d) it matches result (incorrect date).
You should use "yyyy-MM-dd HH:mm:ss.SSS", but also trim "2016-09-23T09:14:52.555000000" to "2016-09-23T09:14:52.555", eg:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.parse("2016-09-23T09:14:52.555000000".substring(0,23));
Milliseconds should be represented in 3 digits only. Change code to:
System.out.println(displayDate("2016-09-23T09:14:52.555"));
System.out.println(displayDate("2016-09-28T11:56:24.552"));
System.out.println(displayDate("2016-09-23T09:29:12.507"));
System.out.println(displayDate("2016-09-26T14:55:02.702"));
System.out.println(displayDate("2016-09-26T09:50:24.880"));
System.out.println(displayDate("2016-09-26T15:20:49.397"));
System.out.println(displayDate("2016-09-26T15:21:21.559"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Getting difference between two Timestamp objects in Java

I'm working on a project, it's about parking and it contains a database. I have variable timestamp for time/date when car enter the parking, and one also for when the car is on the exit.
I want to get difference in hours (minute after every full hour is a new hour etc. 4 hours and 2 mins are same as 5 hours) so I can calculate price of the service (hours multiply by price per hour).
Help me pls, and thank you in advance
get difference in milliseconds and calculate as below
long timeDiff = endTime.getTime() - startTime.getTime()
int hours = (int)Math.ceil(timeDiff/1000*60*60) //In here we are converting milli seconds difference to hours and then if it is not an exact number we are converting that to the next integer
After obtaining the time value in milliseconds (e.g. using a Date object) use TimeUnit to get the difference in times:
TimeUnit.HOURS.convert(timeOut.getTime()-timeIn.getTime(), TimeUnit.MILLISECONDS);

How I can find out difference of days between two dates in Java

Hi I have to find out days difference b/w two dates .First one is current date and
second Date i am taking from database.Actually i want to send Automatic email at difference of 90 days b/w these two dates . Java 1.6 is using in my Application.
I am using this code
for(BidderHeaderBean checkBean:tenderheadersbean){
Date currentdate=new Date();
String datePattern = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(datePattern);
String bidopeningdate= MisUtility.convertDateToString(checkBean.getBidOpeningDate());
Date givenDate = df.parse(bidopeningdate);
Long last = givenDate.getTime();
Long current=currentdate.getTime();
Long timediff=last-current;
Long diffdays=timediff/(1000 * 60 * 60 * 24);
}
I am not getting difference of days.Please help me .
Thanks & Regards
Bhagwan singh
You are probably doing this the wrong way anyway, do a database query to give you every result where the difference is > 90 days.
Assuming you really need to do it this way (for example you've already loaded these records into Java anyway) then the correct way is to use a Calendar or the new java Time API to do all the maths for you. Take the first date, add 90 days to it, see if it is after or before the second date.

Android: Format milliseconds into >60 seconds when no minute format is given

I got a millisecond value. I want to use a format string, to format those milliseconds into a time format. e.g. 45000ms = 45s or 0m 45s or whatever. So this is no special thing. I used SimpleDateFormat for this, but now comes my problem:
61000ms ends up in 1m 1s. This is okay for me, IF there is a minute given in the format string. But when there is no minute given in the format string, it should print out 61s instead of just 1s.
Is there any easy way to achieve this? Currently I dont see it without doing any ugly string formatting code.
I hope you can help me :)
Thanks in advanced!
slain
Edit:
For better understanding:
you got 65400 milliseconds.
format string has minutes, seconds, milliseconds: 1m 5s 400ms
format string has minutes and seconds: 1m 5s
format string has seconds: 65s
format string has seconds and milliseconds: 65s 4ms
format string has minutes and milliseconds: 1m 5400ms
I'm not sure what exactly you are trying to convert but have a look at time units.
If I understand correctly, you are given a number of milliseconds, and a time format string, and need to produce a correctly formatted time? If not, ignore the rest of this...
Maybe not the BEST way, but kind of a nice waterfall: Convert the milliseconds to a set of integers for days, hours, minutes, seconds (or more, or less, depending on the expected range), and then iterate forward through the format string. If day is present, great, stick the number of days in there. If not, skip it, multiply by 24 and add to hours. Do the same for hours->minutes, minutes->seconds, and you should end up with it correctly formatted, even if with weird formats (like days and seconds but not minutes).
Not exactly sure what you're looking for, but you can parse milliseconds like so;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd MMM yyyy");
public static void main(String[] args) {
final long millis = System.currentTimeMillis();
System.out.println(DATE_FORMAT.format(new Date(millis))); // Prints 05 Aug 2011
}
Obviously, you can tweak the date format as necessary to display seconds, milliseconds, etc.

Categories

Resources