我有两个不同的字符串,一个用于日期,另一个用于时间。 我把两者结合起来了,我想从中得到一个NSDate。
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *format = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd" options:0 locale:[NSLocale currentLocale]];
[formatter setDateFormat:format];
NSString *date = [formatter stringFromDate:temp];
NSLog(@"%@",date); //This shows 10/11/2013
NSDateFormatter *formatterTime = [[NSDateFormatter alloc] init];
NSString *formatTime = [NSDateFormatter dateFormatFromTemplate:@"j:mm" options:0 locale:[NSLocale currentLocale]];
[formatterTime setDateFormat:formatTime];
NSDate *tTime = [formatterTime dateFromString:[self.arrayOrari objectAtIndex:a]];
NSString *time = [formatterTime stringFromDate:tTime];
NSLog(@"%@",time); //This shows 6:58 PM
NSString *dateTime = [NSString stringWithFormat:@"%@ %@",date,time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd j:mm" options:0 locale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:formatString];
myMed.orario = [dateFormatter dateFromString:dateTime];
NSLog(@"%@",myMed.orario); //This shows NULL
我已经尝试了大约四个小时,但我无法解决这个问题。 有什么想法吗?
更新: 我按照建议尝试了这个:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *format = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd" options:0 locale:[NSLocale currentLocale]];
[formatter setDateFormat:format];
NSString *date = [formatter stringFromDate:temp];
NSLog(@"%@",date); //This shows 10/11/2013
NSDateFormatter *formatterTime = [[NSDateFormatter alloc] init];
NSString *formatTime = [NSDateFormatter dateFormatFromTemplate:@"HH:mm" options:0 locale:[NSLocale currentLocale]];
[formatterTime setDateFormat:formatTime];
NSDate *tTime = [formatterTime dateFromString:[self.arrayOrari objectAtIndex:a]];
NSString *time = [formatterTime stringFromDate:tTime];
NSLog(@"%@",time); //This shows 18:58
NSString *dateTime = [NSString stringWithFormat:@"%@ %@",date,time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd HH:mm" options:0 locale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:formatString];
myMed.orario = [dateFormatter dateFromString:dateTime];
NSLog(@"%@",myMed.orario); //This shows NULL
答案 0 :(得分:2)
你的错误已经结束了:
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"yyyy-MM-dd j:mm" options:0 locale:[NSLocale currentLocale]];
而不是
@"yyyy-MM-dd j:mm"
尝试:
@"yyyy-MM-dd hh:mm"
答案 1 :(得分:1)
好的,我终于做到了!
最终的格式化字符串必须是:“MM / dd / yyyy HH:mm”。我确实尝试使用“MM-dd-yyyy HH:mm”,但它不起作用,我不得不使用精确的分隔符。