我有一个字符串,表示军事时间中存储的日期。我想在12小时的时间内在标签中显示这个字符串。这是我的代码片段:
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:timeZone];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
NSLog(@"Current Date: %@", [dateFormat stringFromDate:[NSDate date]]);
NSLog(@"Sent date: %@",[myPlanData valueForKey:@"planDate"]);
NSDate *aDate =[dateFormat dateFromString:[myPlanData valueForKey:@"planDate"]];
NSLog(@"Converted date is: %@",aDate);
NSString *planDateString = [dateFormat stringFromDate:aDate];
NSLog(@"The converted date string is: %@",planDateString);
planDateLabel.text=planDateString;
输出结果为:
当前日期:06/28/2012 10:08:48 - (所以我的日期格式化程序显示正确吗?)
发送日期:06/30/2012 20:47:34 - (这是发送的值)
转换日期是:( null) - (这是它破坏的地方!)
转换后的日期字符串为:(null)
如果我将dateformat更改为
[dateFormat setDateFormat:@“MM / dd / yyyy HH:mm:ss”];
一切顺利,但我最终显示军事时间。我只想把它转移到12小时的时间并显示在标签上
答案 0 :(得分:1)
这就是我最终如何解决它
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:timeZone];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSDateFormatter *dateFormatback = [[NSDateFormatter alloc] init];
[dateFormatback setTimeZone:timeZone];
[dateFormatback setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSLog(@"Current Date: %@", [dateFormat stringFromDate:[NSDate date]]);
NSLog(@"Sent date: %@",[myPlanData valueForKey:@"planDate"]);
NSDate *aDate =[dateFormat dateFromString:[myPlanData valueForKey:@"planDate"]];
NSLog(@"Converted date is: %@",aDate);
NSString *planDateString = [dateFormatback stringFromDate:aDate];
NSLog(@"The converted date string is: %@",planDateString);
planDateLabel.text=planDateString;
不确定这是否是最佳或正确的方法,但它有效!