Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the date is today or not

I am getting the current date like below:

public void getCurrentDate(View view) {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat mdformat = new SimpleDateFormat("yyyy / MM / dd ");
    String strDate = "Current Date : " + mdformat.format(calendar.getTime());
    display(strDate);
}
private void display(String num) {
    TextView textView = (TextView) findViewById(R.id.current_date_view);
    textView.setText(num);
}

But I want to check whether the date is today's date or not. But I am not getting how to check that.

like image 504
Ravi kumar Avatar asked Oct 28 '25 19:10

Ravi kumar


2 Answers

You can do as @aliaksei's answer, which works fine. But in Android you can also use java.time (API level 26) or ThreetenABP if java.time is not available.

But first you must consider the fact that "today's date" is relative. Now, at this very moment, each part of the world might be in a different "today". In America and Europe it's April 10th, but in some parts of the Pacific it's already April 11th.

You can choose a specific timezone, or just use the device's zone, which I think it's the case. In this case, just use the JVM default timezone.

Then you use the ThreetenABP to convert the Calendar to a LocalDate and then compare with today's date:

// calendar I want to check
Calendar cal = ...

// convert to LocalDate
LocalDate date = DateTimeUtils.toZonedDateTime(cal).toLocalDate();

// compare with today (now() is using the JVM default timezone)
if (date.isEqual(LocalDate.now(ZoneId.systemDefault()))) {
    // today
}
like image 64
paulXkt Avatar answered Oct 30 '25 09:10

paulXkt


public static boolean isSameDay(Calendar cal1, Calendar cal2) {
    if (cal1 == null || cal2 == null) {
        throw new IllegalArgumentException("The dates must not be null");
    }
    return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
            cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
            cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}

Or you could use the DateUtils class that this snippet is from :)

like image 35
aliaksei Avatar answered Oct 30 '25 08:10

aliaksei