Objective - C - 添加类目 - NSDate

Posted on 2016-02-19 17:40  揍揍揍揍揍揍揍小屁孩  阅读(189)  评论(0编辑  收藏  举报

 1.类目为系统内部的类或者是没有源代码的类添加方法,不有添加实例变量

 2.添加的方法会成为原类的一部分,子类照样可以使用

 3.类目的文件名为原类名+文件名

 4.既可以添加实例方法,也可以添加类方法

 

Xcode工程下;  

1 command + N 新建 

2 选择 Objectiove-C File

3 File:  设置新建的类的名字; File  Type:Category(选择) Class:(选择具体要创建的类名)

//关于日期的一些设置: 

   //NSDate 这个类 是Foundation框架中表示日期的类

    //获取当前时间,打印信息包含,年月日 时分秒 以及时区。零时区时间

    NSDate *nowDate = [NSDate date];

    NSLog(@"nowDate is %@",nowDate);        

    //获取明天当天的时间

    NSDate *tomorrow = [NSDate dateWithTimeInterval:24*60*60 sinceDate:nowDate];

    NSLog(@"tomorrow is %@",tomorrow); 

 

    NSTimeInterval seconds = [nowDate timeIntervalSinceDate:tomorrow];

    NSLog(@"%.2f",seconds);//一年一共的秒数 

    NSTimeInterval time = [nowDate timeIntervalSince1970];

    NSLog(@"%.2f",time);    

    //NSDateComponentsFormatter 创建日期格式类,作用是 将NSDate对象 与 NSString 对象 互转

    //1 创建一个 日期格式的对象

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    

    //2 设置转化格式

    /*

     1 y 年

     2 M 月

     3 d 日

     4 H 24小时 h(am/pm 12小时)

     5 m 分

     6 s 秒

     */ 

    [dateFormatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];    

    //使用日期格式对象 完成转换

    //1 将日期对象转化为字符串对象

    NSString *str = [dateFormatter stringFromDate:nowDate];//日期型转化为字符型

    NSLog(@"str is %@",str);    

    NSLog(@"----1");

    //2 将字符串转化为对象

    NSDate *date = [dateFormatter dateFromString:@"2016-01-01 11:11:33"];

    NSLog(@"date is %@",date);

 

//此方法是把 日期类型的数据转化为  字符串类型

+ (NSString *)stringWithDate:(NSDate *)date formatter:(NSString *)formatter{    

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:formatter];//设置日期格式

    NSString *string = [dateFormatter stringFromDate:date];//日期型转化为字符型    

    return string;    

}

//此方法是把字符串类型的数据  转化为日期类型的数据

+ (NSDate *)dateWithDateStringT:(NSString *)string{    

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//必须有的步骤创建格式

    NSDate *date = [dateFormatter dateFromString:string];    

    return date;

}

 

//字符串转化为日期,并且字 符串的格式 可以灵活使用 在外部写

+ (NSDate *)dateWithDateString:(NSString *)string formatter:(NSString *)formatter{    //类方法    

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:formatter];//必须有的步骤..灵活的使用

    NSDate *date = [dateFormatter dateFromString:string];    

    return date;    

}

 

Copyright © 2024 揍揍揍揍揍揍揍小屁孩
Powered by .NET 8.0 on Kubernetes