NSDateFormatter “Month” in 3 letters instead of full word

你说的曾经没有我的故事 提交于 2019-12-03 05:36:29

问题


    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-YYYY HH:mm"];        
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];

If i choose MM i get the month in number: 09-05-2012 15:33 If i choose MMMM i get the month in word: 09-May-2012 15:33

What i wanted, was the month in 3 letters abbreviation.
Eg: January would be Jan

In this case May is correct because it only has 3 letters.


回答1:


Have you tried: [formatter setDateFormat:@"dd-MMM-YYYY HH:mm"]; and then [formatter stringFromDate:someNSDate];




回答2:


IF you get the two things in the wrong order, you don't get the expected output.

[formatter setDateFormat:@"MMM"];
[formatter setDateStyle:NSDateFormatterMediumStyle];

does NOT give the same results as:

[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setDateFormat:@"MMM"];

(The second of these two snippets is now happily handing out Sep Oct etc in my app)




回答3:


In SWIFT

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "dd MMM yyyy HH:mm"

dateFormatter.stringFromDate(NSDate())



回答4:


This is a stripped down solution that works with Swift 4 in producing a 3 letter month output:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM YYYY, HH:mm:ss"

And to verify:

print(dateFormatter.string(from: Date())) // 20 Mar 2018, 23:41:40

As previously noted, MMM is the correct syntax for getting the desired month output.




回答5:


Actually you can set your dateStyle to medium (ie 'Jan', 'Feb' etc) like this:

[formatter setDateStyle:NSDateFormatterMediumStyle];



回答6:


for swift 4 go with:

if let dateFormatter = DateFormatter(){
    dateFormatter.dateStyle = .medium
    // eventually:
    //let locale = Locale(identifier: ...                       
    //dateFormatter!.locale = locale
    dateFormatter.dateStyle = .medium
    dateFormatter!.dateFormat = "dd MMM YYYY, HH:mm:ss"
 } else..
        ..



回答7:


For those who do not get a full month strong with "MMM", you can get it with

dateFormatter.dateFormat = "dd MMMM yyyy"

Tested on Swift 4.2



来源:https://stackoverflow.com/questions/10518659/nsdateformatter-month-in-3-letters-instead-of-full-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!