文章

NSDate和NSString相互转换

NSDate到NSString的转换:

1
2
3
4
5
6
7
8
9
//获取系统当前时间
NSDate *currentDate = [NSDate date];
//用于格式化NSDate对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; <!--more-->    //设置格式:zzz表示时区
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
//NSDate转NSString
NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
//输出currentDateString
NSLog(@"%@",currentDateString);

NSString到NSDate的转换:

1
2
3
4
5
6
7
//需要转换的字符串
NSString *dateString = @"2015-06-26 08:08:08";
 //设置转换格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//NSString转NSDate
NSDate *date=[formatter dateFromString:dateString];

刚刚在线 上的介绍: https://www.superqq.com/

本文由作者按照 CC BY 4.0 进行授权