I am working on Calendar project and I am wondering is there any build in function available in class Calendar
in android which can change daily basis or weekly basis.
For eg I am storing a data in today's date. And I want to repeat that operation on daily basis or weekly basis. I don't want to use Calendar api.
eg
let's say my Calendar instance variable storing date "2014-26-01"
so I want to do something like
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**/
}
You can use the calendar.add() method to increase or decrease the date. for example:
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 getYesterday(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE,-1);
//return the calendar with the date of yesterday
return calendar;
}
By the way, the Joda-Time libary offers convenient plusDays
, plusWeeks
, and plusMonths
methods for such calculations.
// 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();
Dump to console…
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.
When run…
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.