格式日期有问题,当我设置生日1月1日在1999年1月1日文本字段上设置的触摸按钮。我在设备上设置区域是丹麦。 这是我的代码:
NSDateFormatter *dateFormatterForDisplay = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatterForDisplay setDateFormat:@"MMMM dd, YYYY"];
self.birthdayPicker.date = birthday;
_birthday = birthday;
self.birthdayTxt.text = [dateFormatterForDisplay stringFromDate:_birthday];
有人帮我解决这个错误,帮助我节省了大量的时间。感谢。
答案 0 :(得分:3)
更改日期格式年份 yyyy 而非 YYYY
NSDateFormatter *dateFormatterForDisplay = [[NSDateFormatter alloc] init];
dateFormatterForDisplay.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatterForDisplay.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatterForDisplay setDateFormat:@"d MMM yyyy"]; // customize the format
NSDate *setCurrentDate = [dateFormatterForDisplay dateFromString:@"1 jan 2000"];
NSLog(@"date ==%@", [dateFormatterForDisplay stringFromDate:setCurrentDate]);
输出为
更新回答
NSDateFormatter *dateFormatterForDisplay = [[NSDateFormatter alloc] init];
dateFormatterForDisplay.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatterForDisplay.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatterForDisplay setDateFormat:@"d MMM yyyy"];
NSDate *setCurrentDate = [dateFormatterForDisplay dateFromString:@"1 jan 2000"];
[dateFormatterForDisplay setDateFormat:@"MMM dd, yyyy"]; // if you want this use like MMMM dd, yyyy
NSLog(@"date ==%@", [dateFormatterForDisplay stringFromDate:setCurrentDate]);
<强>输出强>
答案 1 :(得分:-1)
而不是设置:
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
尝试使用:
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
它将从设备
设置您的本地时区