我正在开发Calendar项目,我想知道android中的类Calendar
中是否有可用的功能,可以每天或每周更改。
例如我在今天的日期存储数据。我想每天或每周重复这项工作。 我不想使用Calendar api。
e.g。
让我说我的日历实例变量存储日期“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**/
}
答案 0 :(得分:1)
您可以使用calendar.add()方法增加或减少日期。 例如:
public void Calendar getTomorrow(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,1);
//return the calendar with the date of tomorrow
return calendar;
}
public void Calendar getY yesterday(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,-1);
//return the calendar with the date of yesterday
return calendar;
}
答案 1 :(得分:1)
顺便说一下,Joda-Time图书馆为这种计算提供了方便的plusDays
,plusWeeks
和plusMonths
方法。
// 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