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;
}
Related
This question already has answers here:
How can I convert a Unix timestamp to DateTime and vice versa?
(21 answers)
Closed 6 years ago.
I need to calculate a expiry date difference.
I will get this epoch time:
1481410800 (06-Dec-2016 (14:42))
now I want to calculate the days until the expiry date (1481410800)
Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy (HH:mm)", Locale.getDefault());
//Expiry Date
long unixSecondsExpiry = 1481410800; //unixSeconds
Date expiryDate = new Date(unixSecondsExpiry*1000L);
long currentDate = now.get(Calendar.SECOND);
long diff = unixSecondsExpiry - currentDate;
long days = diff / (24l * 60l * 60l * 1000l);
String formattedExpiryDate = sdf.format(expiryDate);
String formattedDateNow = sdf.format(new Date());
Log.w("RUNTEST", "formattedDateNow: " + formattedDateNow);
Log.w("RUNTEST", "formattedExpiryDate: " + formattedExpiryDate);
Log.w("RUNTEST", "days: " + days);
I keep getting 17 days but it should be 5 days till expiry.
RUNTEST: formattedDateNow: 06-Dec-2016 (14:42)
RUNTEST: formattedExpiryDate: 11-Dec-2016 (07:00)
RUNTEST: days: 17
Here you are using new Date()
String formattedDateNow = sdf.format(new Date());
but the calculation is using
long currentDate = now.get(Calendar.SECOND);
Why not just use
long currentDate = new Date().getTime ();
edit
getting the SECONDS from a calendar is just getting the current seconds counter
Field number for get and set indicating the second within the minute.
E.g., at 10:04:15.250 PM the SECOND is 15.
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 7 years ago.
Could anyone please help me out for calculating Date difference in terms of no of days in an efficient way?
Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;
//diff in msec
long diff = currentDate.getTime() - nextCollectionDate.getTime();
//diff in days
long days = diff / (24 * 60 * 60 * 1000);
You can use JodaTime which is a very useful API for these scenarios
int days = Days.daysBetween(date1, date2).getDays();
or else you can create your own method and get the difference
public long getDays(Date d1, Date d2)
{
long l = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(l, TimeUnit.MILLISECONDS);
}
I would suggest you to use LocalDate in Java 8:
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
System.out.println("No of days: " + days);
which as expected will print:
No of days: 1
You can use joda api
Below code should solve your query
Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
Days d = Days.daysBetween(new DateTime(nextCollectionDate ), new DateTime(currentDate ))
int daysDiff = d.getDays();
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
i'm trying the get the Difference between 2 dates time..
i have an arraylist, each object contains data of type Date..
My Questions are:
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date & Time
2) should i fill manually the data in variable of Date, as follows:
Date currentDate = new Date();
currentDate.setMinutes(Calendar.getInstance().get(Calendar.MINUTE));
currentDate.setHours(Calendar.getInstance().get(Calendar.HOUR));
currentDate.setDate(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
currentDate.setMonth(Calendar.getInstance().get(Calendar.MONTH));
currentDate.setYear(Calendar.getInstance().get(Calendar.YEAR));
3) How to get the Difference between the currentDate and the an old date i have
is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date
JavaDoc from java.util.Date empty constructor:
Allocates a Date object and initializes it so that it represents the
time at which it was allocated, measured to the nearest millisecond.
3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
Date oldDate = ...
Date currentDate = new Date();
long dt = currentDate.getTime() - oldDate.getTime();
1) To get the current date:
Date = new Date();
2) TO set manually a Date it is better to work with a Calendar.
Calendar c = new GregorianCalendar();
c.set(Calendar.MONTH, 1);
c.set(Calendar.YEAR, 2015);
// ... and so on
Date date = c.getTime();
3) to calculate the distance in ms between two dates.
Date d1 = ....;
Date d2 = ....;
long distance = d1.getTime() - d2.getTime();
Try this, variable now below is current date.
String givenDate = "03/11/2015";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = (Date)dateFormat.parseObject(givenDate);
Date now = new Date();
System.out.println(date);
System.out.println(now);
int diffInDays = (int)( (now.getTime() - date.getTime())
/ (1000 * 60 * 60 * 24) );
System.out.println(diffInDays);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can choose any format and add time or AM/PM, see more details of SimpleDateFormat. If you dont have string dates then you can directly use date variable shown above.
Cheers !!
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
This question already has answers here:
Difference in days between two dates in Java?
(19 answers)
Closed 8 years ago.
i am trying to get the difference between two dates. one of the dates was parsed from a string(dateEmployd) and the other date is the current date (currentDate). This is what i did to get the dates...
public static Date getActiveService(String DtEmplydString){
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");//formater for parsed String date
Date dateEmployd, currentDate,periodDifference = null;
try{
dateEmployd = ft.parse(DtEmplydString);
currentDate = new Date();
}catch(ParseException e){
JOptionPane.showMessageDialog(null, e);
}
return periodDifference;
}
Now, i am meant to return periodDifference but i dont know how i would find the difference betweent the two dates (dateEmployd and currentDate) and display it in years or days or a combination of both.
please guys much help is needed. thanks in advance...
Take a look at the jodatime library. They have functions like
DateTime dateEmployd = DateTimeFormat.forPattern("yyyy-MM-dd").parse(DtEmplydString);
Years.yearsBetween(dateEmployd, DateTime.now())
The same for Days.daysbetween, Seconds, Hours etc.
long diff = date2.getTime() - date1.getTime();
You could try out the Java.Calendar for date functions because Date is deprecated .
Here is an example with Cdate comparators
Calendar start = Calendar.getInstance();
start.setTime(from ( your initial Date object here ) );
Calendar end = Calendar.getInstance();
end.setTime(new Date());
int actualDays = start.compareTo(end);