假设用户在“系统偏好设置”的“语言和区域”部分设置了自定义日期格式。屏幕截图 - http://imgur.com/gallery/dMy8u
我在NSString表示(eg - @"201603/11"
)中有这个日期,我想把它转换成我自己的日期格式,即“MM / dd / yyyy”。我正在使用以下代码:
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MM/dd/yyyy"
options:0
locale:[NSLocale systemLocale]];
[formatter setDateStyle:NSDateFormatterShortStyle];
NSDate *localDate = [formatter dateFromString:@"201603/11"];
但是localDate总是返回nil。
简而言之,我的NSString表示是201603/11(由用户设置的格式),我想在NSDate表示中得到它。
答案 0 :(得分:0)
// User Date format
NSDateFormatter *userFormatter = [NSDateFormatter new];
[userFormatter setDateFormat: @"yyyyMM/dd"];
NSDate *localDate = [userFormatter dateFromString:@"201610/31"];
NSLog(@"%@",localDate); //You will get, Year: 2016, Month:10, Day: 31
// The date format you want
NSDateFormatter *myFormatter = [NSDateFormatter new];
[myFormatter setDateFormat: @"MM/dd/yyyy"];
// Get date string from your local date object
NSString *myDateString = [myFormatter stringFromDate:localDate];
NSLog(@"%@",myDateString); //You will get a string, 10/31/2016