Time difference in Java [duplicate] - java

This question already has answers here:
How do I measure time elapsed in Java? [duplicate]
(15 answers)
Closed 6 years ago.
Why the output of the Java code below is 04:18:23 and not 03:18:23?
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long duration = end.getTime() - start.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(duration);
System.out.println(sdf.format(cal.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}

Because that's not how you get a duration. Change your code to this:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long duration = end.getTime() - start.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(duration);
System.out.println(new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(cal.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
You'll see it prints out 1969 12 31 19:18:23. That's a date not a duration. Since you're skipping the date components when you print out your answer, it appears like it's printing out a duration, but it's really not.
To be frank, I don't know how to do this in java. I just use the JodaTime library. There's a class called Duration that makes this easy. Here's a SO question that shows how to use it to print out the results any way you want: "pretty print" duration in java

Alternatively, if you don't want to use JodaTime, it's pretty simple to compute the hours, minutes, and seconds from a duration in milliseconds:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long durationMs = end.getTime() - start.getTime();
final int oneHourMs = 3600000;
final int oneMinuteMs = 60000;
final int oneSecondMs = 1000;
long hours = durationMs / oneHourMs;
long minutes = (durationMs % oneHourMs) / oneMinuteMs;
long seconds = (durationMs % oneMinuteMs) / oneSecondMs;
System.out.format("%02d:%02d:%02d", hours, minutes, seconds);
// outputs: 03:18:23
}

Problems:
You are cramming a time-of-day value into a date-time object.
You are using notoriously troublesome old date-time classes, now legacy, supplanted by the java.time classes.
The LocalTime class represents a time-of-day value without a date and without a time zone.
LocalTime start = LocalTime.parse( "00:44:16" );
LocalTime stop = LocalTime.parse( "04:02:39" );
The Duration represents a span of time not attached to the timeline.
Duration duration = Duration.between ( start , stop );

Related

Subtract time in date value

I actually have found the last three dates and what I want to do is subtract 5 hours and 45 minutes from each date. How can implement it?
The code I have done so far is:
public static List<Date> getPastThreeDays() {
List<Date> pDates = new ArrayList<Date>();
for (int i = 1; i <= 3; i++) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -i);
Date date = cal.getTime();
String pastDate = sdf.format(date);
Date pstThreesDates;
try {
pstThreesDates = sdf.parse(pastDate);
pDates.add(pstThreesDates);
} catch (ParseException e) {
e.printStackTrace();
}
}
return pDates;
}
public static void main(String[] args) throws ParseException {
// for getting past three dates
System.out.println("-----Formatted Past Three Days-----");
List<Date> pastThreeDatesList = getPastThreeDays();
for (Date date : pastThreeDatesList) {
System.out.println("Orignal:" + date);
}
You can use the API DateTime from JodaTime and make something like this:
Date date = new Date();
DateTime dateTime = new DateTime(date);
DateTime newDateTime = dateTime.minusHours(5).minusMinutes(45);
How about stay out of dependencies?
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -i);
Calendar calLess5_45 = Calendar.getInstance();
calLess5_45.setTimeInMillis(cal.getTimeInMillis() - (1000*60*45) - (1000*60*60*5));
or with Date:
Date initialDate = cal.getTime();
Date dateLess5_45 = new Date(initialDate.getTime() - (1000*60*45) - (1000*60*60*5));
convert the date into milliseconds then substract the 5hr 45min from it as follows:
public static void main(String[] args) {
System.out.println("-----Formatted Past Three Days-----");
List<Date> pastThreeDatesList = getPastThreeDays();
for (Date date : pastThreeDatesList) {
System.out.println("Orignal:"+date);
long mDateMills= date.getTime() - ((5*3600 *1000)+ 45*60*1000); //you convert your date to millisecond then subtract 5h45min( in milliseconds from it)
String mNewDate= millsToDateFormat(mDateMills);
System.out.println("new Date:"+mNewDate);
}
}
public static String millsToDateFormat(long mills) {
Date date = new Date(mills);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateFormatted = formatter.format(date);
return dateFormatted;
}
java.time
The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
A time zone is crucial in determining a date and in adding subtracting days. The date, and length of day, varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtNow = ZonedDateTime.now( z );
Subtract a day. Accounts for anomalies such as Daylight Saving Time.
ZonedDateTime zdtYesterday = zdtNow.minusDays( 1 );
Subtract a duration of five hours and forty-five minutes.
Duration d = Duration.ofHours( 5 ).plusMinutes( 45 ); // or Duration.parse( "PT5H45M" ) in standard ISO 8601 string format.
ZonedDateTime zdtEarlier = zdtYesterday.minus( d ) ;

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

How to get the time difference in seconds? [duplicate]

This question already has answers here:
Java-How to calculate accurate time difference while using Joda Time Jar
(2 answers)
Closed 7 years ago.
I have used Jodha Library and tried to get the difference between two dates in seconds. But it is only accurate up to the date. Not to the seconds.
public static int getDateDifference(DateTime dateCreatedPa)
{
LocalDate dateCreated = new LocalDate (dateCreatedPa);
LocalDate now = new LocalDate();
Seconds secondsBetween = Seconds.secondsBetween(dateCreated, now);
return secondsBetween.getSeconds();
}
///code calling the above method
DateTime dateCreated=new DateTime(drivingLicense.getDateCreated());
int dateDiff=Common.getDateDifference(dateCreated);
request.setAttribute("dateDiff", dateDiff);
System.out.println("Timestamp: "+dateDiff);
This shows the date difference. But if I give different times on the same date for comparison, it returns 0.
LocalDate is just that, date only, no time information. Use LocalDateTime instead
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.joda.time.Seconds;
public class Test {
public static void main(String[] args) {
DateTime today = DateTime.now();
today = today.minusDays(5);
int dateDiff = getDateDifference(today);
System.out.println("Timestamp: " + dateDiff);
}
public static int getDateDifference(DateTime dateCreatedPa) {
LocalDateTime dateCreated = new LocalDateTime(dateCreatedPa);
LocalDateTime now = new LocalDateTime();
System.out.println(dateCreated);
System.out.println(now);
Seconds secondsBetween = Seconds.secondsBetween(dateCreated, now);
return secondsBetween.getSeconds();
}
}
Outputs...
2015-02-27T15:20:56.524
2015-03-04T15:20:56.628
Timestamp: 432000

Java Date is giving incorrect time difference, jumps 1 hour ahead

My time difference is showing an incorrect output, I'm trying to calculate the time difference between startTime and endTime.
Date time1, time2;
long difference;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
public Time(String startTime, String endTime)
{
this.startTime = startTime;
this.endTime = endTime;
time1 = new Time("16:30", "18:00"); //example
try
{
time1 = df.parse(startTime);
time2 = df.parse(endTime);
}
catch(Exception e) {
System.out.println("invalid time");
}
}
public String getDifference()
{
difference = (time2.getTime() - time1.getTime());
return df.format(difference); //output = 02:30, should be 01:30
}
I know that Joda-Time could make this easier, but I'm supposed not to use any other library.
It calculates the difference correctly as 5400000 milliseconds (1.5 hours), but formats it as 02:30, due to, I think, the time zone.
Add this line in your constructor to set the date format to the UTC time zone, and it should output 01:30 as you expect:
df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
Time is the number of milliseconds since a moment called epoch. In your code, you calculate the difference between to moments, and then interpret the result as a timestamp, but it isn't.
The calculated result is the difference between two timestamps in milliseconds. If you want that printed in hours and minutes, do something like:
public String getDifference() {
difference = (time2.getTime() - time1.getTime()) / 1000L;
long hours = difference/3600;
difference %= 3600;
long minutes = difference/60;
difference %= 60;
long seconds = difference;
return String.format("%d:%02d:%02d", hours, minutes, seconds);
}
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Demo:
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m", Locale.ENGLISH);
LocalTime begin = LocalTime.parse("16:30", dtf);
LocalTime end = LocalTime.parse("18:00", dtf);
Duration duration = Duration.between(begin, end);
System.out.println(duration);
// Custom format
// ##########################################Java-8##########################################
System.out.println(String.format("%d:%d", duration.toHours(), duration.toMinutes() % 60));
// ##########################################################################################
// ##########################################Java-9##########################################
System.out.println(String.format("%d:%d", duration.toHoursPart(), duration.toMinutesPart()));
// ##########################################################################################
}
}
Output:
PT1H30M
1:30
1:30
Learn about the modern date-time API from Trail: Date Time.

Check if current time is more than an hour from "last_updated" time

On my Android App, I'd like to only re-import my data if it's been at least X hours since the last import.
I'm storing the last_updated time in my sqlite database in this format: 2012/07/18 00:01:40
How can I get "hours from then" or something like that?
My code thus far:
package com.sltrib.utilities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateHelper
{
public static String now()
{
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
//System.out.println("Now the date is :=> " + dateNow);
return dateNow;
}
public static int hoursAgo(String datetime)
{
//return the number of hours it's been since the given time
//int hours = ??
//return hours;
}
}
You're going to want to do math between two Calendars or Dates.
Note: Aspects of Date are deprecated, see below for Calendar!
Here's an example using Date:
public static int hoursAgo(String datetime) {
Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime); // Parse into Date object
Date now = Calendar.getInstance().getTime(); // Get time now
long differenceInMillis = now.getTime() - date.getTime();
long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
return (int)differenceInHours;
}
There are some try/catch blocks involved here (which you should probably handle with throws), but this is the basic idea.
Edit: Since parts of Date are deprecated, here is the same method using Calendar:
public static int hoursAgo(String datetime) {
Calendar date = Calendar.getInstance();
date.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime)); // Parse into Date object
Calendar now = Calendar.getInstance(); // Get time now
long differenceInMillis = now.getTimeInMillis() - date.getTimeInMillis();
long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
return (int)differenceInHours;
}
You can also do it directly on the query. Look this question, there is examples of how to calculate difference between two dates:
SQLite: express the difference as days, hours, minutes between two given dates

Categories

Resources