Format a date from a string

前端 未结 5 1876
盖世英雄少女心
盖世英雄少女心 2020-12-10 08:37

I\'m trying to format a date from a string into another format.

For example: 2012-05-29 23:55:52 into 29/05 *newline* 2010.

I just

5条回答
  •  死守一世寂寞
    2020-12-10 09:11

    You will need to create an NSDateFormatter, and then set it's dateFormat to match the first date you have, eg:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    

    That will set your date formatter to recognise your date string. You can then obtain an NSDate object from this using

    NSDate *myDate = [dateFormatter dateFromString:myDateString]; // myDateString is the 2012-05-29 23:55:52 string
    

    This gives you a full NSDate object representing that date. Now you need to reformat the date and turn it back into a string, so set the dateFormat on your formatter to the new format, and get a new string representation of the returned date:

    [dateFormatter setDateFormat:@"dd/MM\nyyyy"];
    NSString *newlyFormattedDateString = [dateFormatter stringFromDate:myDate];
    [dateFormatter release], dateFormatter = nil;
    

    And voila! You have your new date :)

提交回复
热议问题