iOS与日期相关的操作

// Do any additional setup after loading the view, typically from a nib.
    //得到当前的日期  注意week1是星期天
    NSDate *date = [NSDate date];
    NSLog(@"date:%@",date);
    
    //得到(24 * 60 * 60)即24小时之前的日期,dateWithTimeIntervalSinceNow:
    NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(24* 60* 60)];
    NSLog(@"yesterday:%@",yesterday);
    
    
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    //NSDate *date_ = [NSDate date];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;

    
    //int week=0;week1是星期天,week7是星期六;
    comps = [calendar components:unitFlags fromDate:date];
    int week = [comps weekday];
    int year=[comps year];
    int month = [comps month];
    int day = [comps day];
    
    //[formatter setDateStyle:NSDateFormatterMediumStyle];
    
    //This sets the label with the updated time.
    
    int hour = [comps hour];
    int min = [comps minute];
    int sec = [comps second];
    NSLog(@"week:%d : %@",week,[self week:week]);
    NSLog(@"year:%d",year);
    NSLog(@"month:%d",month);
    NSLog(@"day:%d",day);
    NSLog(@"hour:%d",hour);
    NSLog(@"min:%d",min);
    NSLog(@"sec:%d",sec);
    
    //得到毫秒
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    //[dateFormatter setDateFormat:@"hh:mm:ss"]
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSLog(@"Date:%@", [dateFormatter stringFromDate:[NSDate date]]);


-(NSString*)week:(NSInteger)week

{
    NSString*weekStr=nil;
    if(week==1)
    {
        weekStr=@"星期天";
    }else if(week==2){
        weekStr=@"星期一";
    }else if(week==3){
        weekStr=@"星期二";
    }else if(week==4){
        weekStr=@"星期三";
    }else if(week==5){
        weekStr=@"星期四";
    }else if(week==6){
        weekStr=@"星期五";
    }else if(week==7){
        weekStr=@"星期六";
    }
    return weekStr;
}

NSDate 转换为NSString:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);


NSString 转换为NSDate:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2010-08-04 16:01:03"];
NSLog(@"%@", date);


iOS与日期相关的操作,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。