NSDate的使用

来源:互联网 发布:淘宝怎么查看旺旺号 编辑:程序博客网 时间:2024/05/17 03:51

转载自:http://blog.csdn.net/cooljune/article/details/18899279


NSDate 是OC中的时间类型,和Java中的Date一样,而对时间进行格式化处理的NSDateFormatter就像Java中simpledateformat,对时间进行格式化输出或者对一个字符串时间转换成时间格式。

基本使用

NSDate *date=[ NSDate date ];

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

        // 1970-1-1 0 0 0 100

        [ NSDate dateWithTimeIntervalSince1970 : 100 ];

        // 比当前时间晚 100

        [ NSDate dateWithTimeIntervalSinceNow : 100 ];

        // 随机返回一个将来的时间

        [ NSDate distantFuture ];

        // 随机访问一个过去的时间

        [ NSDate distantPast ];

        

        NSDate *date2=[ NSDate date ];

        

        // 返回早一点的时间

        NSLog ( @"%@" ,[date earlierDate :date2]);

        // 返回晚一点的时间

        NSLog ( @"%@" ,[date laterDate :date2]);

        

        // 返回从 1970 到现在的秒数

        NSLog ( @"%zd" ,[date timeIntervalSince1970]);

格式化使用

// 格式化 HH24 小时 hh12 小时

        NSDateFormatter *format=[[[ NSDateFormatter alloc ] init ] autorelease];

        format. dateFormat = @"yyyy-MM-dd hh:mm:ss";

        //时间转字符串输出

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

        

        NSString *times= @"2014-02-02 12:10:25";

        //字符串转时间

        NSLog ( @"%@" ,[format dateFromString :times]);


0 0
原创粉丝点击