有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java每周或每月更改日期

我正在做日历项目,我想知道安卓中的类Calendar中是否有内置函数可以每天或每周更改

例如,我将数据存储在今天的日期中。我想每天或每周重复这个操作。 我不想使用日历api

例如

假设我的日历实例变量存储日期“2014-26-01”

所以我想做一些类似的事情

final Calendar c = Calendar.getInstance();

for(int i = o ; i <= 30 ; i++){


    yy = c.get(Calendar.YEAR);
    mm = c.get(Calendar.MONTH);
    dd = c.get(Calendar.DAY_OF_MONTH);

    Toast.makeText(this,yy+"-"+mm+"-"+dd,Toast.LENGH_SHORT).show();
    /** here i want to change the value of `Calendar c` to next day or next week**/
}

共 (2) 个答案

  1. # 1 楼答案

    你可以使用日历。add()方法来增加或减少日期。 例如:

    public void Calendar getTomorrow(){

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE,1);
    
    //return the calendar with the date of tomorrow
    return calendar;
    

    }

    公共无效日历GetDayed(){

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE,-1);
    
    //return the calendar with the date of yesterday
    return calendar;
    

    }

  2. # 2 楼答案

    顺便说一下,Joda-Time库为此类计算提供了方便的plusDaysplusWeeksplusMonths方法

    // java.util.Date dateNow = new java.util.Date();
    // Convert a java.util.Date to Joda-Time. Simply pass Date to constructor.
    // DateTime now = new DateTime( dateNow, DateTimeZone.forID( "Europe/Paris" ) );
    
    DateTime now = new DateTime( DateTimeZone.forID( "Europe/Paris" ) );
    DateTime tomorrow = now.plusDays( 1 );
    DateTime nextWeek = now.plusWeeks( 1 );
    DateTime firstMomentOfNextWeek = now.plusWeeks( 1 ).withTimeAtStartOfDay();
    DateTime nextMonth = now.plusMonths( 1 );
    
    // Convert from Joda-Time back to old outmoded bundled Java class, java.util.Date.
    java.util.Date dateNow = now.toDate();
    

    转储到控制台

    System.out.println( "now: " + now );
    System.out.println( "now in UTC/GMT: " + now.toDateTime( DateTimeZone.UTC ) );
    System.out.println( "tomorrow: " + tomorrow );
    System.out.println( "nextWeek: " + nextWeek );
    System.out.println( "firstMomentOfNextWeek: " + firstMomentOfNextWeek );
    System.out.println( "nextMonth: " + nextMonth );
    System.out.println( "dateNow: " + dateNow ); // Remember, a j.u.Date lies. The `toString` applies default time zone, but actually a Date has no time zone.
    

    跑步时

    now: 2014-01-27T00:06:41.982+01:00
    now in UTC/GMT: 2014-01-26T23:06:41.982Z
    tomorrow: 2014-01-28T00:06:41.982+01:00
    nextWeek: 2014-02-03T00:06:41.982+01:00
    firstMomentOfNextWeek: 2014-02-03T00:00:00.000+01:00
    nextMonth: 2014-02-27T00:06:41.982+01:00
    dateNow: Sun Jan 26 15:06:41 PST 2014