iOS NSDateFormatter将一串字符串转换成时间格式

来源:互联网 发布:mac os 英文字体 编辑:程序博客网 时间:2024/04/29 23:33

   NSString * timeString = @“2013071718:24:03.0”;

    NSDateFormatter *inputFormatter = [[[NSDateFormatteralloc]init] autorelease];

    [inputFormatter setLocale:[[[NSLocalealloc]initWithLocaleIdentifier:@"en_US"]autorelease]];

    [inputFormatter setDateFormat:@"yyyyMMddHH:mm:ss.0"];//这里将字符串中的时间格式排列处理,以便系统认知

    NSDate* inputDate = [inputFormatter dateFromString:timeString];

    

    NSDateFormatter *outputFormatter = [[[NSDateFormatteralloc]init] autorelease];

    [outputFormatter setLocale:[NSLocalecurrentLocale]];

    [outputFormatter setDateFormat:@"yyyy.MM.dd"];//这里可以设置任意时间格式,即想要得到的时间格式

    NSString *str = [outputFormatter stringFromDate:inputDate];


 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: 毫秒

常用日期结构:
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
MM dd yyyy