-3

I would like to know if the date changed because I need to refresh a variable the next day.

    Date currentTime = Calendar.getInstance().getTime();
    date = (TextView) findViewById(R.id.currentTime);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault());
    date.setText(dateFormatter.format(currentTime));
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
asia92
  • 5
  • 4
  • 1
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 14 '19 at 05:06

2 Answers2

1

tl;dr

localDate.isBefore( LocalDate.now() )

java.time.LocalDate

You are using terrible date-time classes that were supplanted years ago by the modern java.time classes. Here you want LocalDate class.

Get today's date using the JVM’s current default time zone.

LocalDate localDate = LocalDate.now() ;

Later, grab the date again, and compare.

boolean newDate = localDate.isBefore( LocalDate.now() ) ;

Or, if you think there is a possibility of the clock being messed up, check for inequality.

boolean dateDiffers = ! localDate.isEqual( LocalDate.now() ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You can do this with SharedPreferences- follow my code

    private SharedPreferences mPrefs;
    private SharedPreferences.Editor editor;
    private String sharedPref = "MY_PREF";
    String REFRESH_DAILY;
    
        REFRESH_DAILY = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()).format(new Date());
         
        //check for first time 
        boolean today_Checkin = mPrefs.getBoolean(REFRESH_DAILY, false);
        if (!today_Checkin  ) {
            //new day is here
        } else {
            Toast.makeText(MainActivity.this, "already done", Toast.LENGTH_SHORT).show();
        }
                
        //when you have done for today      
        editor = mPrefs.edit(); 
        editor.putBoolean(REFRESH_DAILY, true);
        editor.apply();
jay patoliya
  • 611
  • 7
  • 8