Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format the current date for the user's locale?

Tags:

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.

like image 355
SpokaneDude Avatar asked Mar 12 '12 23:03

SpokaneDude


People also ask

How do I get a locale date?

Use the toLocaleString() method to get a date and time in the user's locale format, e.g. date. toLocaleString() . The toLocaleString method returns a string representing the given date according to language-specific conventions.

Which method convert date to string in current user's locale?

DateTime. parse - gives invalid date time error. DateTime. valueOf.

What is locale date?

The LOCALE functions take an alphanumeric item (a character string) in the format of a date, for the LOCALE-DATE intrinsic function, or in the format of a time, for the LOCALE-TIME intrinsic function and return another alphanumeric item with the date or time formatted in a culturally appropriate way.


1 Answers

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:

NSDate* now = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
NSString* myString = [df stringFromDate:now];

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

like image 116
JiaYow Avatar answered Nov 01 '22 10:11

JiaYow