Determining the latest of two dates, using Calender - android

I have two instances of Calender, expiryDate and nowDate. The date of expiryDate is set to 16 august 2020, nowDate gets the current date.
Calendar expiryDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
expiryDate.set(Calendar.DAY_OF_MONTH, 16);
expiryDate.set(Calendar.MONTH, Calendar.AUGUST);
expiryDate.set(Calendar.YEAR, 2020);
What code can determine which instance has the latest date?

First Convert your Calendar to date Object.
Date date1 = calendar.getTime();
then use date compareTo method.
Date class has its own methods for date comparison: compareTo
if (date1.compareTo(date2) > 0) {
Log.i("app", "Date1 is after Date2");
}

Best and easiest, get epoch millis from both and compare the long millis
Calendar expiryDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
expiryDate.set(Calendar.DAY_OF_MONTH, 16);
expiryDate.set(Calendar.MONTH, Calendar.AUGUST);
expiryDate.set(Calendar.YEAR, 2020);
long nowMillis = nowDate.getTimeInMillis();
long expiryDateMillis = expiryDate.getTimeInMillis();
if(nowMillis>expiryDateMillis){
//now date is after expiry
}else{
//now date is before expiry
}

Simplest way is use milliseconds Kotlin:
if (expiryDate.timeInMillis< nowDate.timeInMillis) {
// Expired
} else {
// Not expired
}
Java
if (expiryDate.getTimeInMillis() < nowDate.getTimeInMillis()) {
// Expired
} else {
// Not expired
}

The implementation of the Calendar.compareTo() function is equivalent to the getTimeInMillis solutions - so why not just use the Calendar's code:
So OP would be:
if (nowDate.compareTo(expiryDate) > 0) {
// expired
} else {
// not expired
}
Note - this does not solve the "same-day" case.
For reference here's the Calendar's implementation of the compareTo:
public int compareTo(Calendar anotherCalendar) {
if (anotherCalendar == null) {
throw new NullPointerException();
}
long timeInMillis = getTimeInMillis();
long anotherTimeInMillis = anotherCalendar.getTimeInMillis();
if (timeInMillis > anotherTimeInMillis) {
return 1;
}
if (timeInMillis == anotherTimeInMillis) {
return 0;
}
return -1;
}

Related

How to compare time ranges?

Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog
start time:06:00
end time:23:00
selected time from time picker dialog:12:23
above timing not suitable for below code can some one help me please
String pattern = "hh:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {
}
else {
Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
}
You can use code below .
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse(startTime);
Date date2 = sdf.parse(endTime);
Date date3 = sdf.parse(selectedTime);
if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
// Do your stuff
} else {
// Wrong time
}
} catch (Exception e) {
e.printStackTrace();
}
h represents Hour in am/pm (1-12)
H represents Hour in day (0-23)
Your date is in 24 hour formate so you should use H instead of h.
You should use compareTo().
CompareTo method must return negative number if current object is less
than other object, positive number if current object is greater than
other object and zero if both objects are equal to each other.
Code Reference
if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2");
}
else
{
Log.d("RESULT","date2 older than date1");
}
NOTE
Make sure your TIME format is perfect.

Calculate daysAgo return wrong days

I'm trying to calculate daysAgo from two dates, the phone date time and my passed date.
this is my code:
int daysAgo = DateUtilities.getTimeAgo(DateUtilities.stringToDateTime(updatedAt, true).getTime());
public static int getTimeAgo(long time) {
if (time < 1000000000000L) {
time *= 1000;
}
long now = System.currentTimeMillis();
if (time > now || time <= 0) {
return 0;
}
final long diff = now - time;
return (int) (diff / DAY_MILLIS);
}
public static Date stringToDateTime(String dateTime, boolean useUtc) throws ParseException {
if (useUtc) {
return new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss").parse(dateTime);
} else {
return new SimpleDateFormat("yyyy-mm-dd").parse(dateTime);
}
}
this code as int daysAgo return wrong days for me, i pass this date to calculate: 2017-11-18T20:31:04.000Z and my phone date time as System.currentTimeMillis() is 1511080129979 and then result of returned daysAgo is 305
You must use "MM" to represent the month, not the "mm". It is for minutes. Your code
return new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss").parse(dateTime);
return new SimpleDateFormat("yyyy-mm-dd").parse(dateTime);
should be changed to
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateTime);
return new SimpleDateFormat("yyyy-MM-dd").parse(dateTime);
The problem over here is pre-optimization.
int daysAgo = DateUtilities.getTimeAgo(DateUtilities.stringToDateTime(updatedAt, true).getTime());
return new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss").parse(dateTime);
The above statements are perfect only when you know what they are doing, otherwise, they are impossible to even debug.
These are the situations where we understand the real importance of TDD.
The TDD approach
DateUtilitiesUnitTest
public class DateUtilitiesUnitTest
{
#Test
public void testStringToDateTimeConversion()
{
Calendar expectedCal = Calendar.getInstance();
// Here we set the month as Calendar.NOVEMBER
// As per the Calendar API, month 11 == DECEMBER
expectedCal.set(2017, Calendar.NOVEMBER, 18, 20, 31, 4);
Date actualDate = DateUtilities.stringToDateTime("2017-11-18T20:31:04.000Z");
Calendar actualCal = Calendar.getInstance();
actualCal.setTime(actualDate);
// Date.equals(Date), compares two Dates with the milliseconds precision, and cannot be used reliably
// hence, we have to compare all the individual elements separately
assertEquals("Year should be 2017", expectedCal.get(Calendar.YEAR), actualCal.get(Calendar.YEAR));
assertEquals("Month should be " + expectedCal.get(Calendar.MONTH), expectedCal.get(Calendar.MONTH), actualCal.get(Calendar.MONTH));
assertEquals("Day should be 18", expectedCal.get(Calendar.DAY_OF_MONTH), actualCal.get(Calendar.DAY_OF_MONTH));
// If required, you may go ahead and compare Hours, Minutes and Seconds
}
}
=== Step 1 (Fail the Test) ===
DateUtilities.java
public static Date stringToDateTime(String dateTime)
{
return null;
}
Test Result
java.lang.NullPointerException
=== Step 2 (Just enough to Pass the test) ===
DateUtilities.java
public static Date stringToDateTime(String dateTime)
{
Calendar cal = Calendar.getInstance();
// Here we set the month as Calendar.NOVEMBER
// As per the Calendar API, month 11 == DECEMBER
cal.set(2017, Calendar.NOVEMBER, 18, 20, 31, 4);
return cal.getTime();
}
Test Result
1 Test passed
Failing and then Passing the "pseudo tests" proves that your Test is actually working and that you are in fact testing the correct method.
=== Step 3 (Start Implementation) ===
DateUtilities.java
public static Date stringToDateTime(String dateTime)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");
Date date = null;
try {
date = format.parse(dateTime);
}
catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Test Result
java.lang.AssertionError: Month should be 10
Expected :10
Actual :0
We caught the issue!
Expected month is 10 (Calendar.NOVEMBER)
but, we got 0 (Calendar.JANUARY)
=== Step 4 (Fix it!) ===
DateUtilities.java
public static Date stringToDateTime(String dateTime)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = null;
try {
date = format.parse(dateTime);
}
catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Test Result
1 Test passed
Just change the date format to
public static Date stringToDateTime(String dateTime, boolean useUtc) throws ParseException {
if (useUtc) {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateTime);
} else {
return new SimpleDateFormat("yyyy-MM-dd").parse(dateTime);
}
}
In date mm denotes to minutes where MM denotes to months.

android get date of up coming Sunday

I am using following code to get date of coming Sunday. Code is working in some devices but in some devices it shows Sunday after coming Sunday. Please help. why it is not working in some devices.
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar c=Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.add(Calendar.DATE,7);
Date currentTime = c.getTime();
date = dateFormat.format(currentTime);
} catch (Exception e) {
e.printStackTrace();
}
private static Calendar getNextSundayDate() {
Calendar calendarForNextSunday = Calendar.getInstance();
int today = calendarForNextSunday.get(Calendar.DAY_OF_WEEK);
//System.out.println("today" + today);
if (today != Calendar.SUNDAY) {
int offset = Calendar.SATURDAY - today + Calendar.SUNDAY;
//System.out.println("offset" + offset);
calendarForNextSunday.add(Calendar.DATE, offset);
//System.out.println("new" + calendarForNextSunday.get(Calendar.DAY_OF_WEEK));
//System.out.println("next sunday" + calendarForNextSunday.get(Calendar.DATE));
}
return calendarForNextSunday;
}
This might work for you
may be the problem of TimeZone ?
try this:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("some time zone"));

Difference in days between two dates not giving proper results

I am trying to find difference in days between two dates.
I am using this approach
Calendar currentTimeCalendar = Calendar.getInstance();
Calendar postModificationTimeCalendar = Calendar.getInstance();
postModificationTimeCalendar.setTime(dateeventoccured); //dateeventoccured is in format = Tue Jan 03 00:44:46 EST 2017
long diffInMillis = currentTimeCalendar.getTimeInMillis() - postModificationTimeCalendar.getTimeInMillis();
long days = diffInMillis/ (24*60*60*1000);
Now the problem is suppose, I posted something yesterday at 5 pm ,When it is 12 in midnight today difference should be 1 and date should be like yesterday.
but the days remains 0 ,until next day 5 is reached.How to achieve that.
I want to show dates as today,yesterday and previous dates.
Try this (pass the 2 dates object in this function and you will get the exact diff. in days between 2 dates) :
public long getDays(Date d1, Date d2) {
if (d1 != null && d2 != null) {
long diff = getStartDate(d1).getTimeInMillis() - getStartDate(d2).getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(diff);
} else {
return -1;
}
}
public Calendar getStartDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
private int getDifferenceDay(Date DateStart, Date DateEnd) {
long diff = DateEnd.getTime() - DateStart.getTime();
long seconds = diff / 1000;
int minutes = (int) seconds / 60;
int hour = minutes / 60;
int day = hour/24;
return day;
}
Try using comareTo method it will return the date difference as integer value.
private void getDate() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-mm");
String date1="2017-13-01";
String date2="2017-14-01";
Date d1=sdf.parse(date1);
Date d2=sdf.parse(date2);
int compare = d2.compareTo(d1);
Log.e("differece",""+compare);
}

Comparing date values

I am using two functions to compare date values where I will be checking to see if start date is greater than/comes after the end date.
The 1st function is used to take in string value and use that string value to initialize the Calendar:
private int getFromCalendar(String strDate,int field)
{
int result = -1;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);//convert to date
Calendar cal = Calendar.getInstance();// get calendar instance
cal.setTime(date);//set the calendar date to your date
result = cal.get(field); // get the required field
return result;//return the result.
}
catch (ParseException e)
{
e.printStackTrace();
}
return result;
}
The 2nd function is used to compare the startDate and endDate (they are both buttons):
public void compareDates(String startDate, String endDate){
Calendar startCheckDate = Calendar.getInstance();
int startmm = getFromCalendar(monitoringDate.getText().toString(), Calendar.MONTH);
int startyy = getFromCalendar(monitoringDate.getText().toString(), Calendar.YEAR);
int startdd = getFromCalendar(monitoringDate.getText().toString(), Calendar.DAY_OF_MONTH);
startCheckDate.set(startyy, startmm, startdd);
Calendar endCheckDate = Calendar.getInstance();
int endmm = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.MONTH);
int endyy = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.YEAR);
int enddd = getFromCalendar(monitoringEndDate.getText().toString(), Calendar.DAY_OF_MONTH);
endCheckDate.set(endyy, endmm, enddd);
if(endCheckDate.after(startCheckDate)){
Toast.makeText(getSherlockActivity(), "End date cannot be smaller than start date", Toast.LENGTH_SHORT).show();
}
}
For some reason the compareDates function does not work at all. Help please
You can easily compare date by changing it to milliseconds since 1900
Date date = new Date();
long dateLong = date.getTime();
Now its easy to compare with any other date
So for your case after doing this get back in date DataType
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");// this is your date format "12/24/2013" = "MM/dd/yyy"
java.util.Date date = formatter.parse(strDate);
do something like
long date1long = date1.getTime();
long date2long = date2.getTime();
if(date2long > date1long)
{
// Do whatever you want
}
This is the easiest way to compare two dates
You are way to verbose. Since you only wanted to know if a given date is after another, or not. Here you go:
public class DateTest {
private static SimpleDateFormat formatter = new SimpleDateFormat(
"MM/dd/yyyy");
public static void main(String[] args) throws ParseException {
Calendar start = createFromString("01/30/2013");
Calendar end = createFromString("06/30/2013");
System.out.println("START: " + start.getTime());
System.out.println("END : " + end.getTime());
System.out.println("IS B4: " + isBefore(start, end));
}
public static Calendar createFromString(String date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(formatter.parse(date));
return c;
}
public static boolean isBefore(Calendar start, Calendar end) {
return start.before(end);
}
}
OUTPUT
START: Wed Jan 30 00:00:00 CET 2013
END : Sun Jun 30 00:00:00 CEST 2013
IS B4 : true
I usesd getTime() in the println() method since, the toString() method (that gets implicitly called) on java.util.Date is more human readable than the one in Calendar.
There is also an after() in Calendar and a compareTo().
in the compareDates() use
if(endCheckDate.compareTo(startCheckDate)<0)
instead of
if(endCheckDate.after(startCheckDate))
for more reference go here

Categories

Resources