Converting NSString to NSDate (and back again)

后端 未结 17 2507
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:26

How would I convert an NSString like \"01/02/10\" (meaning 1st February 2010) into an NSDate? And how could I turn the NSDat

17条回答
  •  梦毁少年i
    2020-11-21 23:54

    using "10" for representing a year is not good, because it can be 1910, 1810, etc. You probably should use 4 digits for that.

    If you can change the date to something like

    yyyymmdd
    

    Then you can use:

    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormat dateFromString:dateStr];  
    
    // Convert date object to desired output format
    [dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
    dateStr = [dateFormat stringFromDate:date];  
    [dateFormat release];
    

提交回复
热议问题