How to handle different date time formats using NSDateFormatter

后端 未结 4 1935
时光说笑
时光说笑 2020-12-15 05:18

I have a String with a datetime format: \"YYYY-MM-DD HH:MM:SS\".

I use this in my source code:

NSDateFormatter *formatter = [[[NSDateFormatter alloc]         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 06:05

    First off, make sure you set the behavior to 10.4 - more modern, works better in my experience.

    [dateTimeFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    

    Next, you can't use the same format to parse and format if they have 2 different string representations, so use 2 formatters, or change the string format between parsing and then formatting.

    Also make sure you consider the formatting options:

    http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

    lowercase is e is the day of week, lowercase d is the day of the month.

    For month, use MMMM, not B.

提交回复
热议问题