这里我得到当前时间并检查它是否是上午/下午格式。如果不是这样,我将24小时时间格式转换为12小时时间格式并手动添加AM / PM。
这是我的代码:
- (NSString *) getCurrentTime {
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"hh:mm:ss a"];
NSString *currentTime = [timeFormatter stringFromDate:today];
currentTime = [self checkTimeFormat:currentTime];
return currentTime;
}
和
- (NSString *) checkTimeFormat:(NSString *) currentTime
{
NSArray *timeArray = [currentTime componentsSeparatedByString:@":"];
int intHour = [[timeArray objectAtIndex:0] intValue];
NSString *lastVal = [timeArray objectAtIndex:2];
if ([lastVal rangeOfString:@"M"].location == NSNotFound) {
if (intHour < 12)
lastVal = [NSString stringWithFormat:@"%@ AM", [timeArray objectAtIndex:2]];
else
lastVal = [NSString stringWithFormat:@"%@ PM", [timeArray objectAtIndex:2]];
}
if (intHour > 12)
intHour = intHour - 12;
currentTime = [NSString stringWithFormat:@"%d:%@:%@", intHour, [timeArray objectAtIndex:1], lastVal];
NSLog(@"Current Time ==>> %@", currentTime);
return currentTime;
}
将NSString转换为NSDate代码:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm:ss a"];
NSDate *testDate = [dateFormatter dateFromString:getCurrentTime];
NSLog(@"testDate => %@", testDate);
如果时间是12小时格式(上午/下午),则testDate值正确。
如果时间是24小时格式,则testDate值为 null
问题是什么?
先谢谢。
答案 0 :(得分:0)
您可以尝试:
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime24 = [timeFormatter stringFromDate:today];
[timeFormatter setDateFormat:@"hh:mm:ss a];
NSDate *currentTime12 = [timeFormatter dateWithString:currentTime24];
NSString *currentTime = [timeFormatter stringWithDate:currentTime12];