[英]How to format date using NSDateFormatter iOS?
I tried to use the NSDateFormatter
to format a date that selected from a UIDatepicker
. 我试图使用NSDateFormatter
格式化从UIDatepicker
中选择的日期。 But the formatted result giving a nil
. 但是格式化后的结果nil
。
-(NSString *)formatDateWithString:(NSString *)date{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MMM-dd HH:mm:ss";
NSDate *formattedDate = [dateFormatter dateFromString:date];
return [dateFormatter stringFromDate:formattedDate];
}
date input is 2016-04-22 16:30:36 +0000
(after selected from UIDatePicker). 日期输入为2016-04-22 16:30:36 +0000
(从UIDatePicker中选择)。 How may I fix this? 我该如何解决?
As mentioned in the comment you can get the NSDate directly from the UIDatePicker and pass that date directly in the formatter 如评论中所述,您可以直接从UIDatePicker获取NSDate并在格式化程序中直接传递该日期
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MMM-dd HH:mm:ss"];
NSString *dateString = [formatter stringFromDate:datePicker.date];//pass the date you get from UIDatePicker
If you want to convert the same way you have mentioned in the question you can try like this: 如果要以与问题中提到的相同的方式进行转换,可以尝试这样:
-(NSString *)formatDateWithString:(NSString *)date{
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
NSDate * convrtedDate = [formatter dateFromString:date];
[formatter setDateFormat:@"yyyy-MMM-dd HH:mm:ss"];
NSString *dateString = [formatter stringFromDate:convrtedDate];
return dateString;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.