I have this code where I'm trying to get the current date and format it in the current locale.
NSDate *now = [NSDate date]; // gets current date
NSString *sNow = [[NSString alloc] initWithFormat:@"%@",now];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"mm-dd-yyyy"];
insertCmd = [insertCmd stringByAppendingString: formatter setDateFormat: @"MM.dd.yyyy"];
I know the last line is wrong, but can't seem to figure it out... "insertCmd" is a NSString that I'm building for a FMDB command.
Help would be greatly appreciated, or a pointer to the "doc" where it's described.
I wouldn't use
setDateFormat
in this case, because it restricts the date formatter to a specific date format (doh!) - you want a dynamic format depending on the user's locale.NSDateFormatter provides you with a set of built-in date/time styles that you can choose from, i.e. NSDateFormatterMediumStyle, NSDateFormatterShortStyle and so on.
So what you should do is:
This will provide you with a string with a medium-length date and a short-length time, all depending on the user's locale. Experiment with the settings and choose whichever you like.
Here's a list of available styles: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/c/tdef/NSDateFormatterStyle
If you want the localized date and time this will give it to you:
The code above does not give you the localized date and time.
Here's a Swift 5 version of @JiaYou's answer:
Here I need date only, so I indicate the
timeStyle
asnone
.In addition to jiayow answer you can specify your custom 'template' to get localized version:
Example usage for US/DE locale: