標籤:objective-c 時間格式化 unix時間戳記
Objective-C 時間操作實用方法總結
根據月頭擷取月尾日期
/** * GetMonthEndDate * 根據月頭擷取月尾日期 * * @param monthBegin 月頭(yyyy-MM-dd HH:mm:ss) * * @return NSDate / nil */+(NSDate *) GetMonthEndDate:(NSString *)monthBegin{ if (![monthBegin isEqualToString:@""]){ NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC+8"]]; [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDateComponents *currentMonth = [[NSDateComponents alloc] init]; currentMonth.month = 1; NSDate *end = [[NSCalendar currentCalendar] dateByAddingComponents:currentMonth toDate:[formatter dateFromString:monthBegin] options:0]; return end; }else return nil;}
根據日期擷取星期
/** * GetWeekForDate * 根據日期擷取星期 * * @param NSString strDate 日期(yyyy-MM-dd) * * @return NSString / empty */+(NSString*) GetWeekForDate:(NSString *) strDate{ if (![strDate isEqualToString:@""]) { //時間格式化 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; //擷取對應時間 [formatter setDateFormat:@"yyyy-MM-dd"]; NSDate *cdate = [formatter dateFromString:strDate]; //擷取時間資訊 [formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"]; NSString *locationString=[formatter stringFromDate: cdate]; NSArray *arrDate = [locationString componentsSeparatedByString:@" "]; NSString *strWeek = [NSString stringWithFormat:@"%@",[arrDate objectAtIndex:1]]; if ([strWeek isEqualToString:@"Sunday"]) return @"周末"; else if ([strWeek isEqualToString:@"Monday"]) return @"周一"; else if ([strWeek isEqualToString:@"Tuesday"]) return @"周二"; else if ([strWeek isEqualToString:@"Wednesday"])return @"周三"; else if ([strWeek isEqualToString:@"Thursday"]) return @"周四"; else if ([strWeek isEqualToString:@"Friday"]) return @"周五"; else if ([strWeek isEqualToString:@"Saturday"]) return @"周六"; else return @""; }else return nil;}
根據目前時間擷取 unix時間戳記
//擷取時間戳記 NSDate *datetime = [NSDate date]; NSTimeZone *zone = [NSTimeZone timeZoneForSecondsFromGMT:8]; NSInteger interval = [zone secondsFromGMTForDate:datetime]; NSDate *localeDate = [datetime dateByAddingTimeInterval: interval]; NSString *unixtime = [NSString stringWithFormat:@"%.f", floor([localeDate timeIntervalSince1970])];
如下文章為本文提供了相當大的協助,表示感謝:
http://book.2cto.com/201304/21439.html
http://blog.sina.com.cn/s/blog_4e24d9c501010lu2.html
Objective-C 時間操作實用方法總結