-1

在这里,我正在获取当前时间并检查其是否为上午/下午格式。如果不是这样,我将 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

问题是什么?

提前致谢。

4

1 回答 1

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];
于 2013-10-05T19:33:55.900 回答