I want a Java program that calculates days between two dates.
Type the first date (German notation; with whitespaces: "dd mm yyyy")
Type the second date.
The program should calculates the number of days between the two dates.
How can I include leap years and summertime?
My code:
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class NewDateDifference {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String[] eingabe1 = new String[3];
while (s.hasNext()) {
int i = 0;
insert1[i] = s.next();
if (!s.hasNext()) {
s.close();
break;
}
i++;
}
System.out.print("Insert second date: ");
Scanner t = new Scanner(System.in);
String[] insert2 = new String[3];
while (t.hasNext()) {
int i = 0;
insert2[i] = t.next();
if (!t.hasNext()) {
t.close();
break;
}
i++;
}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert1[0]));
cal.set(Calendar.MONTH, Integer.parseInt(insert1[1]));
cal.set(Calendar.YEAR, Integer.parseInt(insert1[2]));
Date firstDate = cal.getTime();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert2[0]));
cal.set(Calendar.MONTH, Integer.parseInt(insert2[1]));
cal.set(Calendar.YEAR, Integer.parseInt(insert2[2]));
Date secondDate = cal.getTime();
long diff = secondDate.getTime() - firstDate.getTime();
System.out.println ("Days: " + diff / 1000 / 60 / 60 / 24);
}
}
UPDATE: The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
LocalDateTime date1 = LocalDate.parse(inputString1, dtf);
LocalDateTime date2 = LocalDate.parse(inputString2, dtf);
long daysBetween = Duration.between(date1, date2).toDays();
System.out.println ("Days: " + daysBetween);
} catch (ParseException e) {
e.printStackTrace();
}
Note that this solution will give the number of actual 24 hour-days, not the number of calendar days. For the latter, use
long daysBetween = ChronoUnit.DAYS.between(date1, date2)
Original answer (outdated as of Java 8)
You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
EDIT: Since there have been some discussions regarding the correctness of this code: it does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:
float days = (diff / (1000*60*60*24));
Note that this is a float value, not necessarily an int.
Simplest way:
public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day.
And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:
Symbol - Meaning - Presentation - Examples
y - year-of-era - year - 2004; 04
M/L - month-of-year - number/text - 7; 07; Jul;
July; J
d - day-of-month - number - 10
Here is the example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Java8DateExample {
public static void main(String[] args) throws IOException {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
final String firstInput = reader.readLine();
final String secondInput = reader.readLine();
final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
System.out.println("Days between: " + days);
}
}
Example input/output with more recent last:
23 01 1997
27 04 1997
Days between: 94
With more recent first:
27 04 1997
23 01 1997
Days between: -94
Well, you could do it as a method in a simpler way:
public static long betweenDates(Date firstDate, Date secondDate) throws IOException
{
return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());
}
Most / all answers caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:
public static int daysBetween(Calendar day1, Calendar day2){
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
//swap them
Calendar temp = dayOne;
dayOne = dayTwo;
dayTwo = temp;
}
int extraDays = 0;
int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);
while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
dayOne.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
}
}
The best way, and it converts to a String as 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);
}
}
Use:
public int getDifferenceDays(Date d1, Date d2) {
int daysdiff = 0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
daysdiff = (int) diffDays;
return daysdiff;
}
Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.
Minimal working example:
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateTestCase {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String firstdate = s.nextLine();
System.out.print("Insert second date: ");
String seconddate = s.nextLine();
// Formatter
DateTimeFormatter dateStringFormat = DateTimeFormat
.forPattern("dd MM yyyy");
DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
int days = Days.daysBetween(new LocalDate(firstTime),
new LocalDate(secondTime)).getDays();
System.out.println("Days between the two dates " + days);
}
}
String dateStart = "01/14/2015 08:29:58";
String dateStop = "01/15/2015 11: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;
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.");
want to get just days(no times) you can use ChronoUnit
ChronoUnit.DAYS.between(date1.toLocalDate(), date2.toLocalDate());
We can make use of LocalDate and ChronoUnit java library, Below code is working fine.
Date should be in format yyyy-MM-dd.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
class Solution {
public int daysBetweenDates(String date1, String date2) {
LocalDate dt1 = LocalDate.parse(date1);
LocalDate dt2= LocalDate.parse(date2);
long diffDays = ChronoUnit.DAYS.between(dt1, dt2);
return Math.abs((int)diffDays);
}
}
When I run your program, it doesn't even get me
to the point where I can enter the second date.
This is simpler and less error prone.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test001 {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");
System.out.println("Insert first date : ");
Date dt1 = sdf.parse(br.readLine().trim());
System.out.println("Insert second date : ");
Date dt2 = sdf.parse(br.readLine().trim());
long diff = dt2.getTime() - dt1.getTime();
System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);
if (br != null) {
br.close();
}
}
}
// date format, it will be like "2015-01-01"
private static final String DATE_FORMAT = "yyyy-MM-dd";
// convert a string to java.util.Date
public static Date convertStringToJavaDate(String date)
throws ParseException {
DateFormat dataFormat = new SimpleDateFormat(DATE_FORMAT);
return dataFormat.parse(date);
}
// plus days to a date
public static Date plusJavaDays(Date date, int days) {
// convert to jata-time
DateTime fromDate = new DateTime(date);
DateTime toDate = fromDate.plusDays(days);
// convert back to java.util.Date
return toDate.toDate();
}
// return a list of dates between the fromDate and toDate
public static List<Date> getDatesBetween(Date fromDate, Date toDate) {
List<Date> dates = new ArrayList<Date>(0);
Date date = fromDate;
while (date.before(toDate) || date.equals(toDate)) {
dates.add(date);
date = plusJavaDays(date, 1);
}
return dates;
}
The following works perfectly well for me:
public int daysBetween(LocalDate later, LocalDate before) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
int daysBetween = 0;
try {
Date dateBefore = myFormat.parse(localDateToString(before));
Date dateAfter = myFormat.parse(localDateToString(later));
long difference = dateAfter.getTime() - dateBefore.getTime();
daysBetween = (int) (difference / (1000 * 60 * 60 * 24));
} catch (Exception e) {
e.printStackTrace();
}
return daysBetween;
}
public String localDateToString(LocalDate date) {
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd MM yyyy");
return date.format(myFormat).toString();
}
All the other answers had lots of scary things, here's my simple solution:
public int getDaysDiff(Date dateToCheck)
{
long diffMilliseconds = new Date().getTime() - dateToCheck.getTime();
double diffSeconds = diffMilliseconds / 1000;
double diffMinutes = diffSeconds / 60;
double diffHours = diffMinutes / 60;
double diffDays = diffHours / 24;
return (int) Math.round(diffDays);
}
public class TestCode {
public static void main(String[] args) {
String date1 = "23-04-2021";
String date2 = "24-05-2021";
System.out.println("NDays: " + nDays_Between_Dates(date1, date2));
}
public static int nDays_Between_Dates(String date1, String date2) {
int diffDays = 0;
try {
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
Date startDate = dates.parse(date1);
Date endDate = dates.parse(date2);
long diff = endDate.getTime() - startDate.getTime();
diffDays = (int) (diff / (24 * 60 * 60 * 1000));
} catch (ParseException e) {
e.printStackTrace();
}
return Math.abs(diffDays);
}
}
Output: NDays: 31
public static String dateCalculation(String getTime, String dependTime) {
//Time A is getTime that need to calculate.
//Time B is static time that Time A depend on B Time and calculate the result.
Date date = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd H:mm:ss");
Date dateObj = null;
Date checkDate = null;
try {
dateObj = sdf.parse(getTime);
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String checkInDate = dateFormat.format(dateObj).toString();
Date defaultTime = null;
try {
defaultTime = dateFormat.parse(dependTime);
checkDate = dateFormat.parse(checkInDate);
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
try {
if (dateFormat.parse(dateFormat.format(date)).after(defaultTime)) {
long diff = checkDate.getTime() - defaultTime.getTime();
Log.e("Difference", "onBindViewHolder: Difference: " + dateObj + " : " + defaultTime + " : " + diff);
if (diff > 0) {
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
return "Late: " + diffHours + " Hour, " + diffMinutes + " Minutes, " + diffSeconds + " Sec";
} else {
return "0";
}
}
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
return "0";
}
Related
i have tried most things online from custom calendar views to dependencies but they all lead to being outdated and not usable for android studio in its latest version.
does anyone know how to achieve this? I have tried mCalendarView, SunDeepK CalendarView and material-calendar view, but to no avail..
private void setCustomResourceForDates() {
Calendar cal = Calendar.getInstance();
//highlighlighting the holidays in a month taking the static dates
ArrayList<String> dates = new ArrayList<String>();
dates.add("02-08-2015");
dates.add("22-08-2015");
dates.add("17-09-2015");
dates.add("25-09-2015");
dates.add("27-09-2015");
dates.add("13-10-2015");
dates.add("22-10-2015");
SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
for (int i = 1; i < dates.size(); i++) {
inputString2 = dates.get(i);
inputString1 = myFormat.format(date);
try {
//Converting String format to date format
date1 = myFormat.parse(inputString1);
date2 = myFormat.parse(inputString2);
//Calculating number of days from two dates
long diff = date2.getTime() - date1.getTime();
long datee = diff / (1000 * 60 * 60 * 24);
//Converting long type to int type
day = (int) datee;
} catch (ParseException e) {
e.printStackTrace();
}
cal = Calendar.getInstance();
cal.add(Calendar.DATE, day);
holidayDay = cal.getTime();
colors();
}
}
public void colors() {
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.green,
holidayDay);
caldroidFragment.setTextColorForDate(R.color.white, holidayDay);
}
}
}
call setCustomResourceForDates(); on onCreate method (in Caldroid Calendar
you can find it here : https://stackoverflow.com/a/32601769/20137896
can you guys help me to displaying the time difference in Java. I've done it but there's some code that should not have to be rewritten.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Time {
public static void main(String[] args) throws Exception {
Date dt = new Date();
DateFormat[] dtformat = new DateFormat[6];
dtformat[0] = DateFormat.getInstance();
dtformat[1] = DateFormat.getDateInstance();
dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL);
dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG);
dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println("Today :");
for(DateFormat dateform : dtformat)
System.out.println(dateform.format(dt));
String str = "May 21 1980";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy");
Date date = df.parse(str);
long epoch = date.getTime();
Date dl = new Date(epoch);
DateFormat[] dlformat = new DateFormat[6];
dlformat[0] = DateFormat.getInstance();
dlformat[1] = DateFormat.getDateInstance();
dlformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dlformat[3] = DateFormat.getDateInstance(DateFormat.FULL);
dlformat[4] = DateFormat.getDateInstance(DateFormat.LONG);
dlformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println("\nDate of Birth :");
for(DateFormat dateform : dlformat)
System.out.println(dateform.format(dl));
System.out.println("\nDifference Days: " + Diff(dl,dt) + " hari");
}
public static long Diff(Date dl, Date dt) {
long diffdays = dt.getTime() - dl.getTime();
long days = diffdays / (24 * 60 * 60 * 1000);
return days;
}
}
The output should be the same, like :
9/24/17 11:31 PM
Sep 24, 2017
Sep 24, 2017
Sunday, September 24, 2017
September 24, 2017
9/24/17
The below code will pretty much does as your code, but removes the repeated section of the logic by moving it to a separated method.Everytime you need to print any date with the specified Date Formats,You can call printDates by passing a Date Object
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Time {
public static void main(String[] args) throws Exception {
Date dt = new Date();
printDates(dt);
String str = "May 21 1980";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy");
Date date = df.parse(str);
long epoch = date.getTime();
Date dl = new Date(epoch);
printDates(dl);
System.out.println("\nDifference Days: " + Diff(dl,dt) + " hari");
}
public static long Diff(Date dl, Date dt) {
long diffdays = dt.getTime() - dl.getTime();
long days = diffdays / (24 * 60 * 60 * 1000);
return days;
}
public static void printDates(Date date){
DateFormat[] dlformat = new DateFormat[6];
dlformat[0] = DateFormat.getInstance();
dlformat[1] = DateFormat.getDateInstance();
dlformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dlformat[3] = DateFormat.getDateInstance(DateFormat.FULL);
dlformat[4] = DateFormat.getDateInstance(DateFormat.LONG);
dlformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println("\nDate of Birth :");
for(DateFormat dateform : dlformat)
System.out.println(dateform.format(date));
}
}
This question already has answers here:
getting the difference between date in days in java [duplicate]
(3 answers)
Calculating the difference between two Java date instances
(45 answers)
Closed 6 years ago.
I have two dates with string format "16-Feb-2017", "26-Feb-2017"
and I used
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
but I am unable to get exact result like "10".
Hope this will help you.pass your dates in myDate and time_ago.
int totalMin;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
Date Date1 = null;
try {
Date1 = sdf.parse(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
Date Date2 = null;
try {
Date2 = sdf.parse(time_ago);
} catch (ParseException e) {
e.printStackTrace();
}
assert Date2 != null;
assert Date1 != null;
long millse = Date1.getTime() - Date2.getTime();
long mills = Math.abs(millse);
Hours = (int) (mills / (1000 * 60 * 60));
Mins = (int) (mills / (1000 * 60)) % 60;
Secs = (int) (mills / 1000) % 60;
long diffDays = millse / (24 * 60 * 60 * 1000);
if (Secs >= 60) {
Mins = Mins + 1;
Secs = Secs - 60;
} else if (Mins >= 60) {
Hours = Hours + 1;
Mins = Mins - 60;
}
totalMin = (int) ((Mins) + (Secs / 60));
String t_time;
if (diffDays > 0) {
if (diffDays == 1) {
t_time = diffDays + " day";
} else {
t_time = diffDays + " days";
}
} else if (Hours > 0) {
if (Hours == 1) {
t_time = Hours + " hour";
} else {
t_time = Hours + " hours";
}
} else if (Mins > 0) {
if (Mins == 1) {
t_time = totalMin + " minute";
} else {
t_time = totalMin + " minutes";
}
} else {
if (Secs == 1) {
t_time = Secs + " second";
} else {
t_time = Secs + " seconds";
}
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
java.time.LocalDate d1 = java.time.LocalDate.parse("16-Feb-2017", formatter);
java.time.LocalDate d2 = java.time.LocalDate.parse("26-Feb-2017", formatter);
Period until = d1.until(d2);
System.out.println("Dif: " + until.getDays());
Please use below code to init SimpleDateFormat.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
As I already said in a comment, use Java 8 java.time classes if you can. kamehl23’s answer shows you how. It’s a both elegant and robust solution, also across changes to and from summer time (DST).
EDIT: Stuck with an older Java version, they say you can use either ThreeTenABP or Joda time, I haven’t tried any of them. ThreeTenABP, I read, is an Android adaption of a backport of java.time to Java 6 and 7, so I would be tempted to give that a shot.
You can of course get through with Java 1.1 Calendar. The solution that also works across summer time change is:
String formattedDate1 = "16-Feb-2017";
String formattedDate2 = "26-Feb-2017";
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", YOUR_LOCALE);
Date d1 = df.parse(formattedDate1);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
Date d2 = df.parse(formattedDate2);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(d2);
int daysBetween = 0;
while (cal1.before(cal2)) {
daysBetween++;
cal1.add(Calendar.DATE, 1);
}
System.out.println(daysBetween);
This prints 10. It’s neither very elegant nor very efficient, but it works robustly as long as the ‘from’ date is before (or the same as) the ‘to’ date (which can easily be checked).
I getting two date from calendars.It writing into a string builder.I want to getting difference between two date also I want to keep the number of days remaining between times,except weekends.
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
if (cur == DATE_DIALOG_ID) {
// set selected date into textview
permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
tvDisplayDate.setText("Date : " + permitDate);
} else {
startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
tvDisplayDate2.setText("Date : " + startDate);
}
}
};
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Use JodaTime library to find the difference between dates.
For more information follow the instructions Use Joda Time.
I have two dates, eg. 1989-3-21, 2016-3-21 and I want to find the duration of difference between those dates. For this I am trying the following code but I am unable to get the duration of difference in 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;
}
Initialize your dates like so before calling public String getTimeDiff(Date dateOne, Date dateTwo):
Date dateOne=null,dateTwo=null;
try {
dateOne = new SimpleDateFormat( "yyyy-MM-dd" ).parse("2016-3-21");
dateTwo = new SimpleDateFormat( "yyyy-MM-dd" ).parse("1989-3-21");
}
catch (ParseException ex) {
}
System.out.println( getTimeDiff(dateOne,dateTwo));
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d date(s) ", TimeUnit.MILLISECONDS.toDays(timeDiff));
return diff;
}
Since your Dates aren't in their default format you will have to use a SimpleDateFormat to explicitly declare the format of your Dates.
From here
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
Try Using This
try {
/// String CurrentDate= "10/6/2016";
/// String PrviousDate= "10/7/2015";
Date date1 = null;
Date date2 = null;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
date1 = df.parse(CurrentDate);
date2 = df.parse(PrviousDate);
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (Exception e) {
System.out.println("exception " + e);
}
Take the difference and and call the method;
long diff = dt2.getTime() - dt1.getTime();
public static String toHumanReadableTime(long diff) {
Long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60 * 60);
Long minutes = TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60);
Long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% 1000;
Long milisec = diff;
StringBuilder buffer = new StringBuilder();
if (hour != null && hour > 0) {
buffer.append(hour).append(" Hour ");
}
if (minutes != null && minutes > 0) {
buffer.append(minutes).append(" Minute ");
}
buffer.append(seconds).append(" Second ");
buffer.append(milisec).append(" Millisecond ");
return buffer.toString();
}