NSDate常用

2017-05-25  本文已影响8人  JC_Wang

NSDate常用

标签(空格分隔): 实用编程习惯-coding


[TOC]


1、字符串与日期的相互转换

        //NSDate求日期
        NSDate *date = [NSDate date];
        NSDateFormatter *fm = [[NSDateFormatter alloc] init];
        fm.dateFormat = @"yyyy-MM-dd HH-mm-ss";
        //-----日期转换成字符串------
        NSDate *lastDate = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];
        NSString *dateString = [fm stringFromDate:lastDate];
        NSLog(@"一天前的日期string :%@",dateString);

        //-----字符串转换成日期------
        NSString *oneDateString = @"2022-12-6 18:01:33";
        fm.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        NSDate *oneDate = [fm dateFromString:oneDateString];

        NSLog(@"未来某天的日期Obj :%@",oneDate);
image_1bgvjtsdmgvh14vk18vm9mmo8f9.png-38.7kBimage_1bgvjtsdmgvh14vk18vm9mmo8f9.png-38.7kB

2、NSDateComponents获取日期

NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *date = [NSDate date];
        //日历集合的结构体
        NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *comp = [calendar components:units fromDate:date];
        NSLog(@"%@",comp);
        NSLog(@"%zd年%zd月%zd日",comp.year,comp.month,comp.day);
image_1bgvkrt2fbt51tkbha3m4tmnhm.png-46.9kBimage_1bgvkrt2fbt51tkbha3m4tmnhm.png-46.9kB

3 获取前一天或者后一天的日期

最low的方式

高b格方式

        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *date = [NSDate date];
        //日历集合的结构体
        NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

        NSDateComponents *components = [[NSDateComponents alloc] init];
        [components setYear:-1];
        [components setMonth:-1];
        NSDate *lastMonth = [calendar dateByAddingComponents:components toDate:date options:kNilOptions];
        components = [calendar components:units fromDate:lastMonth];
        NSLog(@"去年的 上一个月 %@",components);
image_1bgvljn2l18qe1ouf1aeudju37013.png-33.7kBimage_1bgvljn2l18qe1ouf1aeudju37013.png-33.7kB
上一篇下一篇

猜你喜欢

热点阅读