NSDate operations (comparison, creation, addition or subtraction of a certain period of time on the existing date), nsdatedate
Current Creation Time
[Cpp]View plaincopyprint?
- NSDate * date = [NSDate date];
24 hours from now on
NSTimeInterval a_day = 24*60*60;
NSDate * tomorrow = [NSDate dateWithTimeIntervalSinceNow: a_day];
Create date based on existing date
[Cpp]View plaincopyprint?
- NSTimeInterval a_day = 24*60*60;
- NSDate * date = [NSDate date];
- NSDate * tomorrow = [date addTimeInterval: date];
Date comparison
[Cpp]View plaincopyprint?
- BOOL isEqual = [date is1_todate: tomorrow];
- F (isEqual ){
- NSLog (@ "equal ");
// Obtain the earlier date
[Cpp]View plaincopyprint?
- NSDate * earlier_date = [tomorrow earlierDate: date];
- NSLog (@ "earlierDate = % @", earlierDate );
// Date later
[Cpp]View plaincopyprint?
- NSDate * laterDate = [tomorrow laterDate: date];
- NSLog (@ "laterDate = % @", laterDate );
// The number of seconds between two dates
[Cpp]View plaincopyprint?
- NSTimeInterval secondsInterval = [date timeIntervalSinceDate: tomorrow];
- NSLog (@ "secondsInterval = % lf", secondsInterval );
// Create a date using the NSCalendar class
[Cpp]View plaincopyprint?
- NSDateComponents * comps = [[NSDateComponentsalloc] init];
- [Comps setMonth: 01];
- [Comps setDay: 31];
- [Comps setYear: 2013];
- NSCalendar * calendar = [[NSCalendaralloc] initWithCalendarIdentifier: NSGregorianCalendar];
- NSDate * date = [calendar dateFromComponents: comps];
// Obtain the date from the existing date
[Cpp]View plaincopyprint?
- Unsigned units = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit;
- NSDateComponents * _ comps = [calendar components: units fromDate: date];
- NSInteger month = [_ comps month];
- NSInteger year = [_ comps year];
- NSInteger day = [_ comps day];
- // NSDateFormatter implements date output
- NSDateFormatter * formatter = [[NSDateFormatteralloc] init];
- [Formatter setDateStyle: NSDateFormatterFullStyle]; // the machine code is output directly.
- // Or manually set the style [formatter setDateFormat: @ "yyyy-mm-dd"];
- NSString * dateString = [formatter stringFromDate: date];
- NSLog (@ "dateString = % @", dateString );
- NSLog (@ "formater = % @", formatter );
// Obtain the date format object
[Cpp]View plaincopyprint?
- -(NSDateFormatter *) getDateFormatter {
- If (dateFormatter = nil ){
- DateFormatter = [[NSDateFormatter alloc] init];
- [DateFormatter setDateStyle: NSDateFormatterMediumStyle];
- [DateFormatter setTimeStyle: NSDateFormatterNoStyle];
- }
- Return dateFormatter;
- }