Show difference in days in Java/ Android [duplicate] - java

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

Related

Why number of days between 2 dates are not coming up correctly? [duplicate]

This question already has an answer here:
This java date arithmetic code gives different answers on different platforms
(1 answer)
Closed 7 years ago.
I am currently trying to get the number of days between 2 dates.
Date1 : 21-JAN-15
Date2 : 23-JUL-15
In my local eclipse tomcat server (in India), I am getting the number of days as: 183 with the following code:
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
Date date1 = new Date("21-JAN-15");
Date date2 = new Date("23-JUL-15");
cal1.setTime(date1);
cal2.setTime(date2);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
When I copy the same java file to a linux server and run the file there using javac and java commands, I get the difference as: 182, which is one day less.
I have confirmed the default timezone of the linux server is EDT using the command: date +%z
I am very confused here. I do not have JODA library in my application and I can't use it. What changes do I need to make to get a uniform result both in my local environment and the linux server? Any help will be appreciated!
Here is a solution using TimeUnit
public static void main(String[] args) {
Date date1 = new Date("21-JAN-15");
Date date2 = new Date("23-JUL-15");
long diffInMillies = date2.getTime() - date1.getTime();
System.out.println(TimeUnit.MILLISECONDS.toDays(diffInMillies));
}
output:
182

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;
}

how do i get the difference between two dates in days in java [duplicate]

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);

Unable to find difference between two dates w.r.t time,seconds,months and years?

This is my java class
public class dateparse {
public static void main(String args[]) throws ParseException
{
Date dd=new Date();
int year = Calendar.getInstance().get(Calendar.YEAR);
int month=0;
int calc_days=0;
String d1 = dd.getDate()+"/"+dd.getMonth()+"/"+year;
String d2 = "19/1/2014";
SimpleDateFormat s1 = new SimpleDateFormat("dd/mm/yyyy");
SimpleDateFormat s2 = new SimpleDateFormat("dd/mm/yyyy");
Date dateOne = new SimpleDateFormat("dd/mm/yyyy").parse(d1);
Date dateTwo = s2.parse(d2);
long diff = dateOne.getTime() - dateTwo.getTime();
calc_days= (int) (diff / 1000 / 60 / 60 / 24 / 1);
}
}
I am trying to find the difference between current date and the date specified with respect to seconds,minutes,hours,days,months and years.Here my input date is 19th Feb 2014.I want to show the difference in no of days(e.g. 10 days) or months+days(e.g.1 month and 2 days) or year+month+days(e.g. 1 year and 2 months and 4 days).But when I run this code it returns difference as -10 days.
Your error is your parsing. Lowercase m means minutes, not month:
SimpleDateFormat s2 = new SimpleDateFormat("dd/mm/yyyy");
should be:
SimpleDateFormat s2 = new SimpleDateFormat("dd/MM/yyyy");
Here's a simplified example:
String d1 = "21/1/2014";
String d2 = "19/1/2014";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date dateOne = sdf.parse(d1);
Date dateTwo = sdf.parse(d2);
long diff = dateOne.getTime() - dateTwo.getTime();
int differenceInDays = (int) (diff / 1000 / 60 / 60 / 24 / 1);
System.out.println(differenceInDays);
Prints: 2
This is a classic error caused by the horrible API that Java has provided:
date.getMonth() returns 0 for January, 1 for february... and 11 for December. If you can, try to avoid java.util.Date and Calendar :P
Attention - Accepted answer is wrong! Prove:
Use as input the dates 2014-03-19 and 2014-04-01 in my timezone "Europe/Berlin". The true answer is 13 days as everyone can easily veryify using standard calendars, but the accepted code of #Duncan produces 12 days because in my timezone there was a dst-jump which breaks the basis of calculation formular (1 day = 24 hours). On 30th of March the day was only 23 hours long.
The JDK pre 8 does not offer a built-in generic solution for this problem. Please also note that your input is just a pair of two plain dates with no time. Therefore it is silly to ask for the difference in seconds, etc. Only asking for the difference in days, months, weeks or years is sensible. In Java 8 you can do following:
// only days
LocalDate start = LocalDate.of(2014, 3, 19); // start in March
LocalDate end = LocalDate.of(2014, 4, 1);
int days = ChronoUnit.DAYS.between(start, end); // 13
// period in years, months and days
LocalDate start = LocalDate.of(2014, 2, 19); // start in February
LocalDate end = LocalDate.of(2014, 4, 1);
Period period = Period.between(start, end); // P1M13D = 1 month + 13 days
Unfortunately you are not free to choose in which calendar units you like to get the difference expressed. JodaTime (and my library) has a more flexible approach using PeriodType.

Subtract two dates in Java [duplicate]

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.");

Categories

Resources