关于日期格式设置及转换

总结一下关于日期格式的问题汇总。code

1.把字符串转化为任意日期时间格式

//将要转换的字符串
 NSString* string = @"20160512134106";
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init] ;
//将要显示日期的时区。
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] ];
//显示日期的格式。
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    NSLog(@"date = %@", inputDate);

Paste_Image.png

链接到上面的代码

    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
//当前的时区
    [outputFormatter setLocale:[NSLocale currentLocale]];
//设置格式
    [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
    NSString *str = [outputFormatter stringFromDate:inputDate];
    NSLog(@"testDate:%@", str);

Paste_Image.png

2.关于NSDateFormatter的格式

G: 公元时代,例如AD公元

    yy: 年的后2位     yyyy: 完全年     MM: 月,显示为1-12     MMM: 月,显示为英文月份简写,如 Jan     MMMM: 月,显示为英文月份全称,如 Janualy     dd: 日,2位数表示,如02     d: 日,1-2位显示,如 2     EEE: 简写星期几,如Sun     EEEE: 全写星期几,如Sunday     aa: 上下午,AM/PM     H: 时,24小时制,0-23     K:时,12小时制,0-11     m: 分,1-2位     mm: 分,2位     s: 秒,1-2位     ss: 秒,2位     S: 毫秒orm

经常使用日期结构: yyyy-MM-dd HH:mm:ss.SSS yyyy-MM-dd HH:mm:ss yyyy-MM-dd MM dd yyyy字符串

3.设置时间延长。

//设置延时的时间
meInterval secondsPerDay = 24 * 60 * 60;

//设置以时间去建立
  NSDate * data = [[NSDate alloc]initWithTimeIntervalSinceNow:-secondsPerDay];
    
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
        [outputFormatter setLocale:[NSLocale currentLocale]];
        [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
 NSString *str = [outputFormatter stringFromDate:data];
    NSLog(@"%@",str);

如今的时间  显示的时间

相关文章
相关标签/搜索