I want to show the date as per Local format of different country.
I got the code from here: Get the user's date format? (DMY, MDY, YMD)
NSString *base = @"MM/dd/yyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString *format = [NSDateFormatter dateFormatFromTemplate:base options:0 locale:locale];
But how can I fetch the order of dd,mm,yyyy
from the format?
This will get you the format of the currentLocale
:
NSString *dateComponents = @"ddMMyyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
To print a NSDate
object in the right format for the currentLocale
try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale currentLocale];
[dateFormatter setLocale:locale];
NSString *dateComponents = @"ddMMyyyy";
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
NSDate* date = [NSDate date];
[dateFormatter setDateFormat:format];
NSString *newDateString = [dateFormatter stringFromDate:date];
NSLog(@"Current date for locale: %@", newDateString);
If you really want the number-order of the dd, MM and yyyy elements it can be done like the following code. It is not(!) pretty and I really think you should reconsider if it is necessary to get the order of the elements.
NSString *dateComponents = @"ddMMyyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
int currentOrder = -1;
int nextIndex = 0;
int dd = -1;
int MM = -1;
int yyyy = -1;
NSString* workingSubstring;
while (dd == -1 || MM == -1 || yyyy == -1)
{
workingSubstring = [[format substringFromIndex:nextIndex] substringToIndex:2];
if ([workingSubstring isEqualToString:@"dd"])
{
dd = ++currentOrder;
nextIndex += 3;
}
else if ([workingSubstring isEqualToString:@"MM"])
{
MM = ++currentOrder;
nextIndex += 3;
}
else if ([workingSubstring isEqualToString:@"yy"])
{
yyyy = ++currentOrder;
nextIndex += 5;
}
}
NSLog(@"dd: %d, MM: %d, yyyy: %d", dd, MM, yyyy);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.