码迷,mamicode.com
首页 > 其他好文 > 详细

Objective-C 时间操作实用方法总结

时间:2015-04-27 09:45:25      阅读:119      评论:0      收藏:0      [点我收藏+]

标签: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 时间操作实用方法总结

标签:objective-c   时间格式化   unix时间戳   

原文地址:http://blog.csdn.net/yimiyuangguang/article/details/45305843

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!