Calculate date difference in days in Android [duplicate] - android

This question already has answers here:
Android difference between Two Dates
(14 answers)
Closed 7 years ago.
I want to calculate the difference between two dates in days.
I have something like:
String deadline = "2015-08-15";
and I get the current date in:
String timeStamp = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
For example it would be for today:
2015-11-11
How can I calculate the days between these two dates? And what happens if the date is past.

I use this
public String getDateAgo() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date date = sdf.parse(createdAt);
Date now = new Date(System.currentTimeMillis());
long days = getDateDiff(date, now, TimeUnit.DAYS);
if (days < 7)
return days + "d";
else
return days / 7 + "w";
} catch (ParseException e) {
e.printStackTrace();
}
return "ERROR";
}
private long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
}

Use jodatime:
String date1 = "2015-11-11";
String date2 = "2013-11-11";
DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime d1 = formatter.parseDateTime(date1);
DateTime d2 = formatter.parseDateTime(date2);
long diffInMillis = d2.getMillis() - d1.getMillis();
Duration duration = new Duration(d1, d2);
int days = duration.getStandardDays();
int hours = duration.getStandardHours();
int minutes = duration.getStandardMinutes();

you can use Calendar Class for this. for past time you can pass day, month and year to Calendar Class and after that you can convert it to milisecond. and you can do this for current time. and after that you can convert it to milisecond. then you have 2 value with milisecond unit. and you can calculate their difference and again you can convert this result milisecond to Date. a reading of Calendar class documentation and it's method can be very useful.

Try this,
public static long getDatesDifferenceInDays(Date startDate,Date endDate) {
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
return elapsedDays;
}

Related

sqlite query to get date difference in android working on netbeans

I am making a reminder app and for that I need to calculate the date difference between the stored date in database with the current date. I have tried the julianday method but it doesn't seems to work. Please give the relevant sqlite query. I am new to android so please help!!!
At First Query Data from database for getting date then convert this date data to Date Format
Covert Date to Date Format
String dateString = "03/26/2012 11:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then get System Current date and Compare database data to System current date.
Date Different Method
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}

how to get correct date diffrence

i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat d = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
SimpleDateFormat ye = new SimpleDateFormat("yyyy");
String day = d.format(c.getTime());
String month = m.format(c.getTime());
String year = ye.format(c.getTime());
int d1=Integer.parseInt(day);
int m1=Integer.parseInt(month);
int d2=25;
int m2=02;
int diff=d1-d2;
String s=String.valueOf(diff);
You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
//your code
}else{
//your code
}
If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;
Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();
You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;
...
int diff = d1 - d2;
if(diff > MONTH) {
//more than a month difference
}
If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.

Subtract two datepickers in android [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 8 years ago.
Is there any way to subtract two dates from picker.
Example:
I will select a date from picker1 and date from picker2.
Then, picker2 - picker1 to get the number of days between these two dates.
20/10/2014
(-) 06/10/2014
--------------
14 days
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}
output is this
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
Answer from this link Android difference between Two Dates
Since not much information is provided, I assume you are using DatePicker
The basic flow is like that:
by calling getDayOfMonth(), getMonth() and getYear() from DataPicker to obtain day, month and year respectively.
after obtaining those information, I think you should be able to calculate the day difference between them.
Just for your reference, the following is a topic about day difference, hope this help.
Difference in days between two dates in Java?
short and simple
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date1 = null;
java.util.Date date2 = null;
try {
date1 = simpleDateFormat.parse("20/10/2014");
date2 = simpleDateFormat.parse("06/10/2014");
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int diffInDays = (int) ((date1.getTime() - date2.getTime())/ (1000 * 60 * 60 * 24));
EDIT :
Hello Uday
it is Very Simple you have two EditText so first Set your date into et and et1 and now
et.getText().toString(); //Do same for et1 also
this mothod will helps you for getting date and now apply to my code

Convert Date to Year and Month

I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017

Android How to change Total number of days into years,months and days exactly?

i am doing an app that is related to get the age of a person according to the given input of birthday date. for that i am getting the total number of days from that date to the current date from the below code.
String strThatDay = "1991/05/10";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
try {
d = formatter.parse(strThatDay);
Log.i(TAG, "" +d);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis();
long days = diff / (24 * 60 * 60 * 1000);
from this code i am getting total number of days. so my requirement is convert the total number of days in to years ,months and days exactly.. please help....
You should use the Duration class :
Duration duration = new Duration();
duration.add( today );
duration.substract( birthDate);
int years = duration.getYears();
int months = duration.getMonths();
int days = duration.getDays();
Some other alternatives include using a library dedicated to time management : Joda time. See Calculate age in Years, Months, Days, Hours, Minutes, and Seconds
String strThatDay = "1991/05/10";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date thatDate = null;
try {
try {
thatDate = formatter.parse(strThatDay);
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(thatDate);
Calendar toDay = Calendar.getInstance();
toDay.setTime(thatDate);
toDay.add(Calendar.DATE, noOfDays);
int year = toDay.getTime().getYear() - thatDay.getTime().getYear();
int month = toDay.getTime().getMonth() - thatDay.getTime().getMonth();
if(month<0){
year--
month = month+12;
}
int days = toDay.getTime().getDate() - thatDay.getTime().getDate();
if(month<0){
month--
days = days+ toDay.getMaximum(Calendar.MONTH);;
}

Categories

Resources