Difference between hh:mm a and HH:mm a
Updated Answer
Here the problem is with Program flow
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
this simple date formatter
is used to format the date string the Date object is created, here is the important part of answer
As you are using HH instead of hh, the SimpleDateFormater considers that provided date string is in 24-Hour Format
and simply ignores the AM/PM marker
here.
The Date Object from constructed from this SimpleDateFormatter is passed to the
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
That's why it's printing
newDate = 23 Dec 2015 01:04 AM
if you change the line
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
with
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
Everything will go smooth as it should!
Note : when creating a locale you should pass the language code to the Locale() constructor. en-us
not en_us
.
IMP : Code is tested on Java 8 also. Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
calculate time difference between two hours in timeformat hh:mm:ss java
The answer by Michael is good (+1). Allow me to add that you don’t need to mention any formatter (though I also see the advantage of being explicit about the format) and you don’t need to invent an artificial and probably incorrect date to deal with the 24:00 issue.
LocalTime start = LocalTime.parse(timeStart);
LocalTime stop = LocalTime.parse(timeStop);
if (stop.isAfter(start)) { // the normal situation
System.out.println(formatDuration(Duration.between(start, stop)));
} else if (stop.equals(LocalTime.MIDNIGHT)) {
System.out.println(
formatDuration(Duration.between(start, stop).plusDays(1)));
} else {
System.out.println("End time " + timeStop + " was before start time " + timeStart);
}
I am assuming that the times are on the same date except that an end time of 00:00:00 would mean midnight at the end of the day (sometimes called 24.00 where I come from). If you need to calculate, say from 13:00 one day to 13:00 to the next day as 24 hours, just delete the second if
condition and the last else
block.
Feeding your example input gives the output you asked for:
04:57:15
01:00:00
12:05:00
11:55:00
As Michael mentions, the toMinutesPart
and toSecondsPart
methods were introduced in Java 9. For how to format the duration in earlier Java versions see my answer here.
What went wrong in your code?
To parse times on a 24 hour clock correctly (12:05:00, 13:00:00, 14:00:00, 15:00:58) you need to use uppercase HH
for hour of day. Lowercase hh
is for hour within AM or PM from 01 to 12 inclusive. When you don’t specify AM or PM, AM is used as default. So 10:03:43 is parsed as you expected. Funnily 15:00:58 is too even though there is no 15:00:58 AM. SimpleDateFormat
just extrapolates. The trouble comes with 12:05:00 since 12:05:00 AM means 00:05:00. On my computer I got 23:55:00 (not 00:05:00, as you said you got). This is because you had first altered the start time into 24:00:00 and next calculated the time from 00:05:00 to 24:00:00, which is 23:55:00. Since you know which time is the start time and which is the end time, you probably shouldn’t swap them in the case where they seem to be in the wrong order. In your last example I got 23:55:00 too. What happens is the same except the times aren’t swapped since 00:05:00 is already before 24:00:00.
Difference between two times stored as Strings
You can do it using SimpleDateFormat
and Date
:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public static long date_hour_diff(String start_date, String end_date) {
SimpleDateFormat simple_date_format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
Date parsed_start_date = simple_date_format.parse(start_date);
Date parsed_end_date = simple_date_format.parse(end_date);
long time_diff = d2.getTime() - d1.getTime();
long diff_hours = (time_diff / (1000 * 60 * 60)) % 24;
return diff_hours;
} catch (ParseException e) {
Log.e(TAG, "Date is not valid.");
}
}
Need to get the time difference between the two dates in hh:mm format
My solution:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeDiff {
public static void main(String[] args) throws ParseException {
// Setup
SimpleDateFormat dateFormat = new SimpleDateFormat(
"MM/dd/yyyy HH:mm:ss");
long second = 1000l;
long minute = 60l * second;
long hour = 60l * minute;
// parsing input
Date date1 = dateFormat.parse("02/26/2014 09:00:00");
Date date2 = dateFormat.parse("02/26/2014 19:30:00");
// calculation
long diff = date2.getTime() - date1.getTime();
// printing output
System.out.print(String.format("%02d", diff / hour));
System.out.print(":");
System.out.print(String.format("%02d", (diff % hour) / minute));
System.out.print(":");
System.out.print(String.format("%02d", (diff % minute) / second));
}
}
Keep in mind, that dates are not as easy as you could expect. There are leap seconds and all kind of weird stuff.
Difference between kk and HH in date formatting java
The two formats essentially do the same thing but differ in how they handle midnight
. kk
will format midnight
to 24:00
whereas HH
will format to 00:00
. The hours in a day in k
are 1-24
and in H
are 0-23
It's always worth checking the java documentation as it generally provides very useful explanations as well as examples of uses.
Related Topics
How to Use a Delimiter with Scanner.Usedelimiter in Java
How to Get the SQL of a Preparedstatement
What Are Classes, References, and Objects
Getting the Text That Follows After the Regex Match
Calculate Size of Object in Java
How to Use Annotations to Define Different Types of Relationships in Hibernate 4 and Spring
Adding Files to Java Classpath at Runtime
Differencebetween Set and List
Remove All Occurrences of Char from String
Arithmeticexception: "Non-Terminating Decimal Expansion; No Exact Representable Decimal Result"
Java Byte Array to String to Byte Array
Border with Rounded Corners & Transparency
How to Get Parameters from the Url with Jsp