Home » Android » java – android get previous date of a corresponding date(not yesterday's date)

java – android get previous date of a corresponding date(not yesterday's date)

Posted by: admin June 15, 2020 Leave a comment

Questions:

Please read question carefully before marking duplicate.

I want previous date of a corresponding date.(Not yesterday’s date)

e.g. If user click button once he will be navigated to another screen and is shown data regarding yesterday.

And if he clicks again the same button on that screen, then data should be shown on day before yesterday….and so on… till data present in my database.

So I want to get previous date of a corresponding date. i.e. if I have date 31 Jan 2014(I’m using format 31012014 to store in db) then i should get date 30012014.

I know how to get yesterday’s date e.g. below code

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -1);
    DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
    String yesterdayAsString = dateFormat.format(calendar.getTime());

which gives dates compared to today but I want previous date compared to some other valid date.

So how to get that.

How to&Answers:

You have to use SimpleDateFormat to convert String > Date, after Date > Calendar, for instance;

String sDate = "31012014";
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
Date date = dateFormat.parse(sDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
String yesterdayAsString = dateFormat.format(calendar.getTime());

Answer:

Use this, Its working and tested code.

private String getPreviousDate(String inputDate){
                inputDate = "15-12-2015"; // for example 
                SimpleDateFormat  format = new SimpleDateFormat("dd-MM-yyyy");  
                try {  
                    Date date = format.parse(inputDate); 
                    Calendar c = Calendar.getInstance();
                    c.setTime(date);

                    c.add(Calendar.DATE, -1);
                    inputDate = format.format(c.getTime());
                    Log.d("asd", "selected date : "+inputDate);

                    System.out.println(date);  
                } catch (Exception e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                      inputDate ="";
                }
                return inputDate;
            }

Answer:

Try this one

    String prevDate;
    Date c = Calendar.getInstance().getTime();
    SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
    String todayDate=df.format(c);

    Date date = null;
    try {
        date = df.parse(todayDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -1);
    prevDate = df.format(calendar.getTime());

    Test=(TextView)findViewById(R.id.test);
    Test.setText(prevDate);

Answer:

tl;dr

Use modern java.time classes. Repeatedly subtract a day to move backwards in time.

LocalDate                          // Represent a date-only value, without time-of-day and without time zone.
.now(                              // Determine the current date as perceived in the wall-clock time used by the people of a particular region (a time zone). 
    ZoneId.of( "Europe/Paris" )    // Use real time zone names in `Continent/Region` format, never 2-4 letter pseudo-zones such as PST, EST, IST, CEST, etc.
)                                  // Returns a `LocalDate` object.
.minusDays( 1 )                    // Move back in time by one day, for yesterday’s date. Returns another separate `LocalDate` object rather than modify the original, per Immutable Objects pattern.
.minusDays( 1 )                    // Continue moving back in time another day.
.minus(
    Period.ofDays( 1 )             // Define a span-of-time as any number of years-months-weeks-days. 
)                                  // Continuing to subtract yet another day.
.toString()                        // Generate text representing that last generated `LocalDate` date-value using standard ISO 8601 format.

When parsing your text inputs.

LocalDate
.parse( 
    "30012014" ,
    DateTimeFormatter.ofPattern( "ddMMuuuu" ) 
)
.minusDay( 1 )
.minus(
    Period.ofDays( 1 )        
)    

java.time

The modern approach uses the java.time classes that years ago supplanted the troublesome old date-time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Date math

Your Question is not clear, but it seems you simply want to increment backwards in time one day at a time. This is quite easy with the LocalDate class offering plus & minus methods.

Call the convenience method, LocalDate::minusDays.

LocalDate yesterday = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).minusDays( 1 ) ;

To move backwards, subtract again.

LocalDate localDatePrior = yesterday.minusDays( 1 ) ;

And continue onwards.

localDatePrior = localDatePrior.minusDays( 1 ) ;

You can soft-code the period of time to subtract using the Period class with the LocalDate.minus method.

Period p = Period.ofDays( 1 ) ;
LocalDate localDatePrior = yesterday.minus( p ) ;

Database

(I’m using format 31012014 to store in db)

Don’t.

To store a date-only value in your database, use a date-only type in your column. In a SQL-compliant database, the type will be DATE for a date-only value.

As of JDBC 4.2 we can directly exchange java.time objects with the database.

myPreparedStatement.setObject( … , localDate ) ;

Retrieval.

LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;

Parsing

But to directly address your current situation, you can parse your string with its peculiar format of DDMMYYYY.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "ddMMuuuu" ) ;
LocalDate localDate = LocalDate.parse( "30012014" , f ) ;
String output = localDate.toString() ;  // Generate text in standard ISO 8601 format.

By the way, rather than invent your own date-time format, always use standard ISO 8601 formats when exchanging date-time values as text. The java.time classes wisely use these formats by default when parsing/generating strings.


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.

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

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

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?

Answer:

You’ve got everything right, except before you “add” -1 days, you need to set it to the date you want (before finding the previous date previous):

Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.JUNE, 9);
calendar.add(Calendar.DATE, -1); 
...

Answer:

First off just as a tip, it is better to store your dates as timestamps like so you won’t be dependent on time formats.

As for your question, just keep your current date in a variable and send it to your method once the button is clicked and then subtract an extra day

Calendar curDate = Calendar.getInstance();
curDate.add(Calendar.DATE, -1);

and use your curDate variable from then on

Answer:

Try this:

final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        String yesterdayAsString = fmtOut.format(calendar.getTime());