時間與文字
//NSString => NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2014-01-02 14:16:30"];
NSLog(@"%@", date);
[dateFormatter release];
//NSDate => NSString
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);
[dateFormatter release];
//時間的比較
//Sample codes
//時間的加減
NSDate * anHourAgo = [now dateByAddingTimeInterval:-60*60];
NSDate * anHourAfter = [now dateByAddingTimeInterval:60*60];
//只取某個時間單位
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit fromDate:record.sleepDate];
index = comps.hour - startComps.hour;
//取得時間差
NSTimeInterVal duration = [now timeIntervalSinceDate:lastTime];
if ([date compare:previousDate] == NSOrderedAscending) {
//TODO:date 比 previousDate 來的小
}
if ([date compare:previousDate] == NSOrderedSame) {
//TODO:date 跟 previousDate 是相同時間
}
if ([date compare:previousDate] == NSOrderedDescending) {
//TODO:date 比 previousDate 來的大
}
date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd";
formatter.timeZone = [NSTimeZone defaultTimeZone];
NSMutableString *dateStr = [NSMutableString stringWithString:[formatter stringFromDate:date]];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:se.wakeUpDate];
[dateStr appendFormat:@" %02d:%02d:00", comps.hour, comps.minute];
formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
沒有留言:
張貼留言