iOS 时间格式化

将日期时间转化为字符串

// 实例化NSDateFormatter
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置日期格式
    [formatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
// 获取当前日期
    NSDate *currentDate = [NSDate date];
    NSString *currentDateString = [formatter stringFromDate:currentDate];
    
    NSLog(@"%@", currentDateString);

将时间字符串转换为日期

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 要转换的日期字符串
    NSString *dateString = @"2011-05-03 23:11:40";
// 设置为UTC时区
// 这里如果不设置为UTC时区,会把要转换的时间字符串定为当前时区的时间(东八区)转换为UTC时区的时间
    NSTimeZone *timezone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

    NSDate *someDay = [formatter dateFromString:dateString];
    NSLog(@"%@", someDay);

时间格式

G:      公元时代,例如AD公元
yy:     年的后2位
yyyy:   完整年
MM:     月,显示为1-12,带前置0
MMM:    月,显示为英文月份简写,如 Jan
MMMM:   月,显示为英文月份全称,如 Janualy
dd:     日,2位数表示,如02
d:      日,1-2位显示,如2,无前置0
EEE:    简写星期几,如Sun
EEEE:   全写星期几,如Sunday
aa:     上下午,AM/PM
H:      时,24小时制,0-23
HH:     时,24小时制,带前置0
h:      时,12小时制,无前置0
hh:     时,12小时制,带前置0
m:      分,1-2位
mm:     分,2位,带前置0
s:      秒,1-2位
ss:     秒,2位,带前置0
S:      毫秒
Z:      GMT(时区)

演练

  • (查看http://blog.csdn.net/crayondeng/article/details/8755306)

你可能感兴趣的:(iOS 时间格式化)