android 获取对应日期的前一个日期(不是昨天的日期)

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

请在标记重复之前仔细阅读问题。

我想要对应日期的前一个日期。(不是昨天的日期)

例如如果用户单击按钮一次,他将被导航到另一个屏幕并显示有关昨天的数据。

如果他再次点击那个屏幕上的同一个按钮,那么数据应该会在前天显示......以此类推......直到数据出现在我的数据库中。

所以我想得到相应日期的前一个日期。即如果我有日期 2014 年 1 月 31 日(我使用格式 31012014 存储在数据库中)那么我应该得到日期 30012014.

我知道如何获取昨天的日期,例如下面的代码

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

它给出了与今天相比的日期,但我想要与其他有效日期相比的前一个日期。

那么如何获得。

您必须使用 SimpleDateFormat 来转换 String > Date,例如在 Date > Calendar 之后;

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());

你已经做对了,除了在你 "add" -1 天之前,你需要将它设置为你想要的日期(在找到之前的日期之前):

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

首先作为提示,最好将日期存储为时间戳,这样您就不会依赖于时间格式。

至于你的问题,只需将你的当前日期保存在一个变量中,并在单击按钮后将其发送到你的方法,然后减去额外的一天

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

并从那时起使用您的 curDate 变量

使用这个,它的工作和测试代码。

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;
            }

试试这个:

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

试试这个

    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);

tl;博士

使用现代 java.time classes。反复减去一天时间倒退。

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.

解析您的文本输入时。

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

java.time

现代方法使用多年前的 java.time classes 取代了麻烦的旧日期时间 classes。

LocalDate

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

时区对于确定日期至关重要。对于任何给定时刻,日期在全球范围内因地区而异。例如,Paris France is a new day while still “yesterday” in Montréal Québec.

午夜后几分钟

如果未指定时区,JVM 将隐式应用其当前默认时区。该默认值可以 change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone 明确作为参数。

指定 proper time zone name in the format of continent/region, such as America/Montreal, Africa/CasablancaPacific/Auckland。切勿使用 ESTIST 等 2-4 字母缩写,因为它们 不是 真实时区,未标准化,甚至不是唯一的(!)。

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

如果你想使用 JVM 当前的默认时区,请求它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为默认值可能会在任何时候 在运行时 中被 JVM 中任何应用程序的任何线程中的任何代码更改。

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

或指定日期。您可以通过数字设置月份,1 月至 12 月的编号为 1-12。

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.

或者,更好的是,使用 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 ) ;

日期数学

您的问题不清楚,但您似乎只是想一次一天地向后递增时间。使用 LocalDate class 提供的 plusminus 方法非常容易。

调用便捷方法,LocalDate::minusDays

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

要向后移动,再次减去。

LocalDate localDatePrior = yesterday.minusDays( 1 ) ;

并继续前进。

localDatePrior = localDatePrior.minusDays( 1 ) ;

您可以使用 Period class with the LocalDate.minus 方法对要减去的时间段进行软编码。

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

数据库

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

不要。

要在数据库中存储仅限日期的值,请在列中使用仅限日期的类型。在符合 SQL 的数据库中,对于仅日期值,类型将为 DATE

从JDBC 4.2开始,我们可以直接与数据库交换java.time对象。

myPreparedStatement.setObject( … , localDate ) ;

检索。

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

正在解析

但要直接解决您当前的情况,您可以使用其特殊格式 DDMMYYYY 来解析您的字符串。

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

顺便说一句,与其发明自己的日期时间格式,不如在将日期时间值作为文本交换时始终使用标准 ISO 8601 格式。 java.time classes 在 parsing/generating 字符串时明智地默认使用这些格式。


关于java.time

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.

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

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与您的数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

在哪里获取java.time classes?

            long calendar=Calendar.getInstance().getTimeInMillis()-1000*60*60*24;
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
            String date = sdf.format(calendar);