Compare two date and get the result in android - android

First , there is a base date for comparsion
Date baseDate = dateFormat.parse("2013-01-01");
And there is a list of event date to compare with the base date e.g.
Date date2 = dateFormat.parse("2013-01-02");
So, I would like to get the compare result (in day unit), in this case it is 1.
And if
Date date3 = dateFormat.parse("2012-12-31");
Then , the result should be -1
How can I achieve that? Tried baseDate .compareTo(date3) but it only return true/false. Thanks for helping

Another option is to call java.util.Date.getTime() in your Date objects, which returns the Date as a millisecond value. You can them calculate (date2.getTime() - baseDate.getTime()) / 24*60*60*1000.
Reference: https://developer.android.com/reference/java/util/Date.html#getTime()

String dateStart = "01/14/2014";
String dateStop = "01/13/2014";
Date d1 = null;
Date d2 = null;
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
}
catch (Exception e){
}

java.util.Date has a compareTo() function that conforms to the Comparable interface. This method returns an integer.

Related

Date is not converting from double milliseconds

How to convert double to date?
"orderDate":1538398507000,
this is how I'm getting date, and I'm converting it to date
Date d = new Date(myOrderDataList.get(position).getOrderDate()*1000);
but it shows 1970 as a year
Try this
private String getStringDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
Since your double represents the number of seconds of you date from now, and the Date constructor in Java is expecting a number of milliseconds since 01-01-1970, you have to multiply your number to get a number of milliseconds (* 1000) and substract that from the current number of milliseconds since 01-01-1970 (System.currentTimeMillis()):
double myDouble = -242528463.775282;
long myLong = System.currentTimeMillis() + ((long) (myDouble * 1000));
System.out.println(myLong);
Date itemDate = new Date(myLong);
String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(itemDate);
System.out.println(myDateStr);
But, the problem with the way you store your dates is that if you are calling this code today and tomorrow it will not return the same date, as the current time is changing. You should use timeIntervalSince1970 instead of timeIntervalSinceNow.

how to find difference between two date Time string?

I am calculating time difference between two dates and time but its restuning invalid difference.
here's my sample date and code to calculate the difference.
loginTime=2016-01-24 12:04:30.16
expiryTime = 2016-01-24 13:04:30.16
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date now = new Date();
try {
Date startDate = simpleDateFormat.parse(loginTime);
Date expireDate = simpleDateFormat.parse(expiryTime);
// String temCurrentDate = new SimpleDateFormat("yyyy-MM-dd").format(now);
// Date currentDate = new SimpleDateFormat("yyyy-MM-dd").parse(temCurrentDate);
// String day_of_week = new SimpleDateFormat("EEEE").format(now);
long difference =startDate.getTime()- expireDate.getTime();
int hour = (int) difference / (60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
Difference between this time is 1 hour but i am getting 11 or 13. Please tell where i am going wrong in this.
Spelling error in your variable:
simpleDateFormat.parse(expiryTime);
Does not match: ExpiryTime = 2016-01-24 13:04:30.16
That's the whole problem.

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: Date (year,month,day) [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 2 years ago.
I want to get the date as a year, month ,day without hours or minutes or any thing else, and I don't want to get the year alone and the month and the day each by its self. Because as a full date I need it to comparison with another date
such as today 28.11.2012 and to compare it to 11.12.2011
as if today minus 11.12.2011 more than 280 day I want to execute some code
you can use SimpleDateFormat.
The basics for getting the current date
DateFormat df = new SimpleDateFormat("MMM d, yyyy");
String now = df.format(new Date());
or
DateFormat df = new SimpleDateFormat("MM/dd/yy");
String now = df.format(new Date());
EDITED :
First of All you have the date in String Formate. you have to Convert into date Formate. try below code to do that. you have apply same for both the String strThatDay & strTodaDay you will get Calender Object for both.
String strThatDay = "2012/11/27";
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);
after that try below code to get Day from two Date :
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
try it out. Hope it will help you.
Always use Simpledateformat(yyyy/mm/dd) for comparision..
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String currentDateandTime = sdf.format(new Date());
Use this currentDateandTime to compare with other date.
I think this may be a solution.U have to get instance of 2 calendar (1 for current date and another for compare date.
Calendar cal1=Calendar.getInstance();
Date dt=null;
try{
dt = sdf.parse(currentDateandTime);
cal1.setTime(dt);
}catch (ParseException e){
e.printStackTrace();
}
int currentDaycmp= cal1.get(Calendar.DAY_OF_MONTH);
int currentMonthcmp=cal1.get(Calendar.MONTH);
int currentYearcmp=cal1.get(Calendar.YEAR);
Calendar cal2=Calendar.getInstance();
Date dtend=null;
try{
dtend = sdf.parse(comparedate);
cal2.setTime(dtend);
} catch (ParseException e) {
e.printStackTrace();
}
int currentDayend= cal2.get(Calendar.DAY_OF_MONTH);
int currentMonend=cal2.get(Calendar.MONTH);
int currentyearend=cal2.get(Calendar.YEAR);
now find the difference
currentDaycmp-currentDayend(your condition)..then execute your block..
U try this..May be meet ur requirement..
You may want to use Joda-Time for this:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy");
LocalDate first = LocalDate.parse("28.11.2012", formatter);
// LocalDate first = new LocalDate(2012, 11, 28);
// LocalDate first = LocalDate.now();
LocalDate second = LocalDate.parse("11.12.2011", formatter);
int daysBetween = Days.daysBetween(first, second).getDays();
You should be aware of that daysBetween is a negative value if the second date is before the first like in this example.
For the given example daysBetween is -353.
You can use the compareTo method.
Firstly, make sure that the two dates you are using have the same format. That is, if one is YYYY,DD,MM then the other would be the same.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
Date firstDate = sdf.parse("2012-11-27");
System.out.println(sdf.format(firstDate));
And then you would do a firsDate.compareTo(SecondDate);
if firstDate.compareTo(SecondDate) < 280 {
...
}
Calendar todayCalendar = new GregorianCalendar();
Calendar pickedDateCalendar = new GregorianCalendar();
todayCalendar.set(currentYear,currentMonth,currentDay);
pickedDateCalendar.set(birthDayDatePicker.getYear(),birthDayDatePicker.getMonth(),birthDayDatePicker.getDayOfMonth());
System.out.println("Days= "+daysBetween(todayCalendar.getTime(),pickedDateCalendar.getTime()));
int Days = daysBetween(todayCalendar.getTime(),pickedDateCalendar.getTime());
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}

How to add part of time in Android

I have a code returning me a string (HH:mm).
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dateObj;
try {
dateObj = curFormater.parse(start);
SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
String newDateStr = postFormater.format(dateObj);
startView.setText(newDateStr);
Emission_start = newDateStr;
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.d(" * Error", e.toString());
}
It works great... But right now I would like to:
add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)
Get current time and calculate difference between current time and time from step 1 (4:10)
Get time difference (from step 2) in minutes!
Thanks for your help!
I haven't tested, but something like this should work:
long newDate = dateObj.getTime() +
(x * 60 * 1000)
long diff =
System.currentTimeMillis() - newDate
double diffInMins = diff / (60.0 * 1000.0)
use Calendar
Calendar calInstance = new GregorianCalendar();
calInstance.setTime(dateObj);
Then add any fragment you want, for minutes do
calInstance.add(Calendar.MINUTE, XX)
To, transform use your formatter
postFormatter.format(calInstance.getTime());
is trivial
Diff in minutes can be calculated easily as well
long diffInMins = (currTimeInMillis - calInstance.getTimeInMillis())/(1000 * 60);

Categories

Resources