获取系统时间/时间比较/自定义时间格式

获取系统时间

#import <Foundation/Foundation.h>

void printDate(NSDate * date) {

    NSDateFormatter *dateFormatter = [NSDateFormatter new];

    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];

    //默认输出 以零时区为基准

    NSLog(@"%@", date);

    //计算机设置时区为基准

    NSLog(@"%@",[dateFormatter stringFromDate:date]);

}

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        

        //获取当前时间

        NSDate *date = [[NSDate alloc] init];

        printDate(date);

        //initWithTimeIntervalSinceNow 从当前时间偏移 单位:秒

        date = [[NSDate alloc] initWithTimeIntervalSinceNow:60];

        printDate(date);

        //initWithTimeIntervalSince1970 从1970-01-01 00:00:00偏移 单位:秒

        date = [[NSDate alloc] initWithTimeIntervalSince1970:60*60*4];

        printDate(date);

    }

    return 0;

}

​时间的比较

#import <Foundation/Foundation.h>

void printDate(NSDate * date) {

 NSDateFormatter *dateFormatter = [NSDateFormatter new];

 [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];

 //计算机设置时区为基准

 NSLog(@"%@",[dateFormatter stringFromDate:date]);

}

int main(int argc, const char * argv[]) {

 @autoreleasepool {

 

 //获取当前时间

 NSDate *dateNew = [[NSDate alloc] init];

 printDate(dateNew);

 NSDate *dateOld = [[NSDate alloc] initWithTimeIntervalSinceNow:-60];

 printDate(dateOld);

 NSDate *dateFuture = [[NSDate alloc] initWithTimeIntervalSinceNow:60];

 printDate(dateFuture);

 //一个时间与另一个时间比较

 double x1 = [dateNew timeIntervalSinceDate:dateOld];

 //一个时间与当前时间比较

 double x2 = [dateFuture timeIntervalSinceNow];

 printf("%lf\n%lf\n",x1,x2);

 

 }

 return 0;

}

自定义时间格式

NSDate *date = [[NSDate alloc]init];NSDateFormatter *dateFormatter1 = [NSDateFormatter new];NSDateFormatter *dateFormatter2 = [NSDateFormatter new];NSDateFormatter *dateFormatter3 = [NSDateFormatter new];NSDateFormatter *dateFormatter4 = [NSDateFormatter new];[dateFormatter1 setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];[dateFormatter2 setDateFormat:@"MM月dd日 HH时mm"];[dateFormatter3 setDateFormat:@"yyyy年MM月dd日"];[dateFormatter4 setDateFormat:@"HH时mm分ss秒"];NSLog(@"%@",[dateFormatter1 stringFromDate:date]);NSLog(@"%@",[dateFormatter2 stringFromDate:date]);NSLog(@"%@",[dateFormatter3 stringFromDate:date]);NSLog(@"%@",[dateFormatter4 stringFromDate:date]);  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,481评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,982评论 19 139
  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 13,946评论 0 15
  • excel单元格自定义格式1 代码结构组成代码码分为四个部分,中间用“;”号分隔,具体如下:正数格式;负数格式;零...
    木先生is澜阅读 8,000评论 0 3
  • 今天,给妈妈打了个电话,其实也没有什么,不过是一些家长里短。自从父亲离开后,我也自觉承担了家里的责任,妈妈也爱什么...
    正在长大的我阅读 336评论 1 1