Subtract two dates in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
I know this might be a duplicate thread. But I am trying to figure out a way to compute the difference between two dates. From jquery the date string is in the format 'yyyy-mm-dd'. I read this as a String and converted to java Date like this
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.getParameter(date2));
I want to compute the difference in the number of days between these two dates.
Note: I cannot use third party API's as those need to reviewed.

Edit 2018-05-28
I have changed the example to use Java 8's Time API:
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

Assuming that you're constrained to using Date, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date2));
long diff = d2.getTime() - d1.getTime();
System.out.println("Difference between " + d1 + " and "+ d2+" is "
+ (diff / (1000 * 60 * 60 * 24)) + " days.");

Related

How to calculate difference in days between two dateboxes in GWT? [duplicate]

This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Closed 7 years ago.
I have 1 datebox (datebox1) in my GWT application, which allows users to set the date in past.
Datebox1 is set to following format (not that it probably matters):
datebox1.setFormat(new DateBox.DefaultFormat (DateTimeFormat.getFormat("EEE, MMM dd, yyyy")));
How do I programatically calculate the difference in days between the date selected in the date box and the current date.
I can't find much on the net and would appreciate a simple example.
The simplest way:
Date currentDate = new Date();
int daysBetween = CalendarUtil.getDaysBetween(myDatePicker.getValue(), currentDate);
the below code block will be useful for you
Date selectedDate = DateBox.getDatePicker().getValue();
Date currentDate= new Date();
long fromDate = selectedDate.getTime();
long toDate = currentDate.getTime();
long diffGap = toDate - fromDate;
long diffDays = diffGap / (24 * 60 * 60 * 1000);
If you know how to extract date from your textbox, you can use the following function to get the time difference between any two dates
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}

Show difference in days in Java/ Android [duplicate]

This question already has answers here:
Calculate elapsed time in Java / Groovy
(16 answers)
Closed 7 years ago.
I want to differentiate between Current Date and Action Date. The difference should be shown as :
3 days ago
4 days ago and son ..
How can I achieve the same in Java using in Android?
It does not work for me and returns the actual date itself:
Date d = Utils.instanceDateFormat().parse(text.toString());
String moments = DateUtils.getRelativeTimeSpanString(d.getTime(), new Date().getTime(), DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL).toString();
Try this
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String currentDateInput = "23 01 1997";
String actionDateInput = "27 04 1997";
try {
Date currentDate = myFormat.parse(currentDateInput);
Date actionDate = myFormat.parse(actionDateInput);
long diff = actionDate.getTime() - currentDate.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
You will have to modify the SimpleDateFormat to fit your needs.
Use this to get the difference between two date objects
public static int getDaysDifference(Date fromDate,Date toDate)
{
if(fromDate==null||toDate==null)
return 0;
return (int)( (toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
}
I think you need to change the minimum resolution of SECONDS_IN_MILLIS to DAYS_IN_MILLIS like this --->
DateUtils.getRelativeTimeSpanString(date , System.currentTimeMillis(), DateUtils.DAYS_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString()
Using that all your future dates will be resolved to in X days and past dates to X days ago with exception of previous day which gets resolved to Yesterday but that would require a minor tweak if you need it to resolve to 1 day ago.
Hope this solves the issue

Can't get the number of days between 2 months - specific case

I have few dates in this format: 31/08/13 and I'm getting tehm from an xls file
What I need to do is to get the previous month and to calculate the days betwen these dates. I really don't know what to do.
Here is what I have tried:
code edited*
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.setTime(row.getCell(0).getDateCellValue());
start.add(start.MONTH,-1);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
if(diffDays < 0){
System.out.println(Math.abs(diffDays));
}
DateFormat dateFormatw = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormatw.format(startDate)+" and "+
dateFormatw.format(endDate)+" is "+
diffDays+" days.");
But it seems wrong. I really can't get my mind on it as I'm so tired. I lost too many hours on this without luck.
I'm trying to get the same date but one month ago and to calculate the days, between these 2 dates endTime and startTime
Please help me!
I don't know what a ProdCalendar is, it's presumably something internal to your project. But the simple way to get the numbers of days between 2 dates, which is (I think) what you want, is this:
//First date
Date d1 = dateFormat.parse("31-10-13");
//Second date
Date d2 = dateFormat.parse("31-08-13");
//Interval:
long intervalMs = d1.getTime() - d2.getTime();
long intervalDays = intervalMs/(1000*60*60*24);
In your code, date22 is initialised just with new date() so it will be the current system time. You are comparing that (in a depracated way) to a date retrieved from the spreadsheet. I also notice that Calendar cal in this line near the start:
Calendar cal = Calendar.getInstance();
cal.setTime(row.getCell(0).getDateCellValue());
Is not used again, so appears to be redundant.
Your code is more complicated than it needs to be, so you need to step back and think about what you want to achieve. Simple code is good code.

Date difference in Java 23 hours day

I have to calculate the difference between to dates, I have found a way but I have this strange result, Am I missing something?
public static void main(String[] args) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long result = format.parse("2012-03-25 24:00").getTime() - format.parse("2012-03-25 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
result = format.parse("2012-03-26 24:00").getTime() - format.parse("2012-03-26 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
}
This is the result:
Difference in hours: 23
Difference in hours: 24
Thanks for the advices, now I'm using the Joda libray, I have this question, when I calculate the difference in this way:
DateTime begin = new DateTime("2012-03-25T00:00+01:00");
DateTime end = new DateTime("2012-03-26T00:00+01:00");
Hours m = Hours.hoursBetween(begin, end);
If I use this way to calculate the hours I get 24 hours (because the DST is not considered I assume)
What class/calculus should I use in order to get as result the 23 hours considering the DST (I have already tried different ways but I don't get it) the Period class?
Thanks for all the help...
Chances are you happen to have picked a date where daylight saving time changed in that time zone, so the day could really have been only 23 hours long. (March 25th 2012 certainly was the DST change date for Europe, e.g. Europe/London. We don't know what your default time zone is though.)
If you set your date format to use UTC, you shouldn't see this effect. (It's somewhat odd to use 24:00 in a string representation, mind you.) It's not clear what your data is meant to represent though, or what you're trying to measure. You should work out what time zone your data is really meant to be in, if you want to work out how much time actually elapsed between those local times.
(As noted in another answer, Joda Time is a much better API in general - but you still need to know how to use it properly, and when trying to work out the actual elapsed time, you'd still have seen the same results here.)
Must place the library file like explained below.
import java.util.Date;
String dateStart = dateChooserCombo1.getText();
String dateStop =dateChooserCombo2.getText();
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
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, ");
jTextField3.setText(""+diffDays);
} catch (Exception e) {
e.printStackTrace();
}

How can I calculate the difference between two dates [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I calculate someone's age in Java?
I have two dates eg 19/03/1950 and 18/04/2011. how can i calculate the difference between them to get the person's age? do I have to keep multiplying to get the hours or seconds etc?
String date1 = "26/02/2011";
String date2 = "27/02/2011";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
You use the classes Date and Duration:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Date.html
http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/datatype/Duration.html
You create Date-objects, then use Duration's methods addTo() and subtract()
The following code will give you difference between two dates:
import java.util.Date;
import java.util.GregorianCalendar;
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
Why not use jodatime? It's much easier to calculate date and time in java.
You can get the year and use the method yearsBetween()

Categories

Resources