IOS> 获取当前系统时间

1. NSDate + NSDateFormatter

    NSDate *date = [NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY/MM/dd hh:mm:ss.SSSSSSSS"];
    NSString *sDate = [format stringFromDate:date];
    NSLog(@"%@",sDate);

 

执行结果:精确到1ms

2015-03-30 21:35:13.799 My Legend[1037:53843] 2015/03/30 09:35:13.79900000

 

2.NSDate + NSCalendar + NSDateComponents

    NSDate *now = [NSDate date];
    NSLog(@"now date is: %@", now);
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond |NSCalendarUnitNanosecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSLog(@"%ld/%ld/%ld %ld:%ld:%ld.%ld",(long)dateComponent.year, (long)dateComponent.month, (long)dateComponent.minute, (long)dateComponent.hour, (long)dateComponent.minute, (long)dateComponent.second, (long)dateComponent.nanosecond);

 
执行结果:精确到1ns

2015-03-30 21:35:13.800 My Legend[1037:53843] now date is: 2015-03-30 13:35:13 +0000

2015-03-30 21:35:13.800 My Legend[1037:53843] 2015/3/35 21:35:13.800027012

 

3.C标准库函数 time

time_t 类型是用来存储从1970年到现在经过了多少秒

        time_t tBuf;
        tBuf=time(NULL);
        NSLog(@"%s", ctime(&tBuf));
        NSString *date = [NSString stringWithCString:ctime(&tBuf) encoding:NSUTF8StringEncoding];
        NSLog(@"%@\n", date);

 执行结果 精确到1s

Sun Aug  2 11:42:01 2015

Sun Aug  2 11:42:01 2015

 

注: 可以用tm提取time时间信息

struct tm {//tm结构
    int tm_sec;     /* seconds after the minute [0-60] */
    int tm_min;     /* minutes after the hour [0-59] */
    int tm_hour;    /* hours since midnight [0-23] */
    int tm_mday;    /* day of the month [1-31] */
    int tm_mon;     /* months since January [0-11] */
    int tm_year;    /* years since 1900 */
    int tm_wday;    /* days since Sunday [0-6] */
    int tm_yday;    /* days since January 1 [0-365] */
    int tm_isdst;   /* Daylight Savings Time flag */
    long    tm_gmtoff;  /* offset from CUT in seconds */
    char    *tm_zone;   /* timezone abbreviation */
};

        //提取从time获取的 time_t类型 时间信息
        struct tm tmBuf;
        tmBuf=*localtime(&tBuf);
        NSLog(@"%d:%d:%d", tmBuf.tm_hour, tmBuf.tm_min,tmBuf.tm_sec);

执行结果

11:57:27

 

原文链接: https://www.cnblogs.com/fortunely/p/4472172.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    IOS> 获取当前系统时间

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/403364

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月21日 上午11:28
下一篇 2023年4月21日 上午11:28

相关推荐