-1

我有两个不同的字符串,一个用于日期,另一个用于时间。我将两者结合起来,我想从中获得一个 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
4

2 回答 2

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"
于 2013-10-11T16:27:42.837 回答
1

好的,我终于做到了!

最终的格式化字符串必须是:“MM/dd/yyyy HH:mm”。我确实尝试使用“MM-dd-yyyy HH:mm”,但它不起作用,我必须使用精确的分隔符。

于 2013-10-11T17:08:36.360 回答