Converting time String to Long generates wrong value - java

I have a time String "00:01:00". When I convert it to long by SimpleDateFormat("HH:mm:ss), I'm getting 10860000 milliseconds, equivalent to 03:01:00.
For "00:59:00" I'm getting "03:57:00", so I don't know what's happening but it's adding 3hours to my milliseconds.
Code:
String time = String.format("%02d",hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", seconds);
tvTimer.setText(time);
try {
DateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
Time timeValue = new Time(formatter.parse(time).getTime());
long initTimer = timeValue.getTime
} catch (ParseException e) {
e.printStackTrace();
}
CountDownTimer:
timer = new CountDownTimer(initTimer, 1000) {
#Override
public void onTick(long l) {
long secondsInMilli = initTimer / 1000;
long minutesInMilli = secondsInMilli / 60;
long hoursInMilli = minutesInMilli / 60;
long elapsedSeconds = secondsInMilli % 60;
long elapsedMinutes = minutesInMilli % 60;
long elapsedHours = hoursInMilli % 60;
tvTimer.setText(String.format("%02d", elapsedHours) + ":" + String.format("%02d", elapsedMinutes) +":" + String.format("%02d", elapsedSeconds));
}

I think you have a time zone problem. The string "00:01:00" does not specify a world time, because there is no time zone on it. The parsing will be done on some default time zone, and your offset is evidently 3 (mine seems to be -5).
If you parse "00:01:00 GMT" with ("HH:mm:ss z"), you get the 60000 milliseconds you expect.

Try setting the Timezone after instantiating the formatter, as next:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
or if you need the local time zone then:
formatter.setTimeZone(Calendar.getInstance().getTimeZone());

Related

How to get Time ago in android? [duplicate]

I have two date like:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
I want to print the difference like:
2d 3h 45m
How can I do that? Thanks!
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}
out put is :
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff = today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
Short & Sweet:
/**
* Get a diff between two dates
*
* #param oldDate the old date
* #param newDate the new date
* #return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
try {
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Usage:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
dateDifference: 2
Kotlin Version:
#ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
This works and convert to String as a Bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
} catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
It will give you difference in months
long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
System.out.println(String.format("%d months", elapsedDays/30));
Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.
String date1 = "20170717141000";
String date2 = "20170719175500";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
Duration diff = Duration.between(LocalDateTime.parse(date1, formatter),
LocalDateTime.parse(date2, formatter));
if (diff.isZero()) {
System.out.println("0m");
} else {
long days = diff.toDays();
if (days != 0) {
System.out.print("" + days + "d ");
diff = diff.minusDays(days);
}
long hours = diff.toHours();
if (hours != 0) {
System.out.print("" + hours + "h ");
diff = diff.minusHours(hours);
}
long minutes = diff.toMinutes();
if (minutes != 0) {
System.out.print("" + minutes + "m ");
diff = diff.minusMinutes(minutes);
}
long seconds = diff.getSeconds();
if (seconds != 0) {
System.out.print("" + seconds + "s ");
}
System.out.println();
}
This prints
2d 3h 45m
In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.
I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.
With Java 9 it will be still a bit easier since the Duration class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.
I use this:
send start and end date in millisecond
public int GetDifference(long start,long end){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(start);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
long t=(23-hour)*3600000+(59-min)*60000;
t=start+t;
int diff=0;
if(end>t){
diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
}
return diff;
}
You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.
You can download class from here: DateTimeDifference GitHub Link
Simple to use
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago
Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
You can compare the example below
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}
Try this out.
int day = 0;
int hh = 0;
int mm = 0;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
Date oldDate = dateFormat.parse(oldTime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
} catch (ParseException e) {
e.printStackTrace();
}
if (mm <= 60 && hh!= 0) {
if (hh <= 60 && day != 0) {
return day + " DAYS AGO";
} else {
return hh + " HOUR AGO";
}
} else {
return mm + " MIN AGO";
}
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
it returns how many days between given two dates, where DateTime is from joda library
I arranged a little. This works great.
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);
String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try {
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
#SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}
Here's the simple solution:
fun printDaysBetweenTwoDates(): Int {
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val endDateInMilliSeconds = dateFormat.parse("26-02-2022")?.time ?: 0
val startDateInMilliSeconds = dateFormat.parse("18-02-2022")?.time ?: 0
return getNumberOfDaysBetweenDates(startDateInMilliSeconds, endDateInMilliSeconds)
}
private fun getNumberOfDaysBetweenDates(
startDateInMilliSeconds: Long,
endDateInMilliSeconds: Long
): Int {
val difference = (endDateInMilliSeconds - startDateInMilliSeconds) / (1000 * 60 * 60 * 24).toDouble()
val noOfDays = Math.ceil(difference)
return (noOfDays).toInt()
}
When you use Date() to calculate the difference in hours is necessary configure the SimpleDateFormat() in UTC otherwise you get one hour error due to Daylight SavingTime.
You can generalize this into a function that lets you choose the output format
private String substractDates(Date date1, Date date2, SimpleDateFormat format) {
long restDatesinMillis = date1.getTime()-date2.getTime();
Date restdate = new Date(restDatesinMillis);
return format.format(restdate);
}
Now is a simple function call like this, difference in hours, minutes and seconds:
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = formater.parse(dateEnd);
Date date2 = formater.parse(dateInit);
String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));
txtTime.setText(result);
} catch (ParseException e) {
e.printStackTrace();
}

passing string values to other function from onclick date listner

I need a date in the format like "yyyyMMDD" so i converted my date in my required format as
String YY = Integer.toString(year);
String MM = String.format("%02d", month + 1);
String DD = String.format("%02d", day);
String selecteddate = YY;
selecteddate = selecteddate.concat(MM);
final String selecteddate1 = selecteddate.concat(DD);
I want to use selecteddata1 AS my from date in finding the date difference.
#Nik,
Try this
DatePickerDialog mDatePicker = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
year = selectedyear;
month = selectedmonth;
day = selectedday;
String date = "" + day + "-" + (month+1) + "-" + year;
stardate.setText(date);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd/M/yyyy");
try {
Date date1 = simpleDateFormat.parse(""+day+"/"+(month+1)+"/"+year");
Date date2 = simpleDateFormat.parse("13/10/2013"); //If you want to use the current date, use "new Date()"
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}, year, month, day);
mDatePicker.setTitle("Please select date");
mDatePicker.getDatePicker().
setMaxDate(System.currentTimeMillis());
mDatePicker.show();
}
});
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}
If you have Calendar object then you can call getTime() method to convert (and format) into any String, e.g.:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMDD");
System.out.println("Formatted date " + dateFormat.format(calendar.getTime()));
System.out.println("Date Object " + calendar.getTime());

Joda time find difference between Hours

I have a date String:
Thu, 15 Jan 2015, 9:56 AM
I convert it into a date variable:
Thu Jan 15 09:56:00 GMT+05:30 2015
using:
String pattern = "EEE, d MMM yyyy, hh:mm a";
try {
date = new SimpleDateFormat(pattern).parse(getPref("refresh", getApplicationContext()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I have the following function and pass the date variable to this below function:
public static int getDiffHour(Date first) {
int hoursBetween = Hours.hoursBetween(new LocalDate(first), new LocalDate()).getHours();
return hoursBetween;
}
Which always returns 0. What is the possible cause?
try like this,
int diff_hrs = getDiffHours(date,new Date());// pass your date object as startDate and pass current date as your endDate
public int getDiffHours(Date startDate, Date endDate){
Interval interval = new Interval(startDate.getTime(), endDate.getTime());
Period period = interval.toPeriod();
return period.getHours();
}
Try below code:-
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.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);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
for more info see below link :-
http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EEE, d MMM yyyy, hh:mm a");
try {
Date date1 = simpleDateFormat.parse("Thu Jan 15 09:56:00 GMT+05:30 2015");
Date date2 = simpleDateFormat.parse("Thu Jan 16 09:56:00 GMT+05:30 2015");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}

Issue with formatting time duaration

Running the following code:
private static String formatDuration(final long duration) {
final long hh = duration / 1000 / 3600;
final long mm = duration / 1000 % 3600 / 60;
final long ss = duration / 1000 % 3600 % 60;
return hh + "h" + ":" + mm + "m" + ":" + ss + "s";
}
private static void printDuartion() throws ParseException{
SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
System.out.println(formatDuration(dayTo-dayFrom));
}
I have the an output:
48h:59m:59s
But actually it should be:
47h:59m:59s
Please help me find out where the mistake is.
Your code is correct, I also get 47h:59m:59s. Demo: http://ideone.com/fxZKba
I can only imagine that you are in a time zone where these days are affected by Daylight saving time. Like "Atlantic/Bermuda" in the following example:
private static void printDuration() throws Exception {
SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
PARSE_FORMAT.setTimeZone(TimeZone.getTimeZone("Atlantic/Bermuda"));
long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
System.out.println(formatDuration(dayTo - dayFrom));
}
In this case I get 48h:59m:59s Demo: http://ideone.com/jQ7sX2

Need to get the time difference between the two dates in hh:mm format

I need to get the time difference between to different dates in HH:MM format.Suppose I had two dates like this
02/26/2014 09:00:00 and 02/26/2014 19:30:00
I need to get the difference in hh:mm like 09:30.
I googled and tried to find solution for this but they are giving the individual hours and minutes.
I am not allowed to use Third party libraries like Joda for this. Can anyone please point me in the right direction?
UPDATE
I tried the following code
public class DateDifferentExample {
/**
* #param args
*/
public static void main(String[] args) {
String dateStart = "02/26/2014 09:00:00";
String dateStop = "02/26/2014 19:05:00";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
System.out.println("Time difference-->"+diff);
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);
int diffInDays = (int) (d2.getTime() - d1.getTime());
System.out.println("Difference--> "+diffInDays);
String difft=diffHours+":"+diffMinutes;
System.out.println("Duration Time:"+difft);
/*System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");*/
//System.out.println("Getting date diff from the other method--->"+calculateDays(d1, d2));
} catch (Exception e) {
e.printStackTrace();
}
}
/*public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}*/
public static long calculateDays(Date dateEarly, Date dateLater) {
return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}
}
try this
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = df.parse("02/26/2014 09:00:00");
Date d2 = df.parse("02/26/2014 19:30:00");
long d = d2.getTime() - d1.getTime();
long hh = d / (3600 * 1000);
long mm = (d - hh * 3600 * 1000) / (60 * 1000);
System.out.printf("%02d:%02d", hh, mm);
prints
10:30
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.
Parse the timestamps into a Date using SimpleDateFormat.
Calculate the difference between dateOne.getTime() and dateTwo.getTime(). The result will be the difference in milliseconds.
Use the TimeUnit instances to convert the milliseconds to hours and minutes.

Categories