【问题标题】:NSString to NSDate return null valueNSString 到 NSDate 返回空值
【发布时间】:2013-10-05 18:32:54
【问题描述】:

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

有什么问题?

提前致谢。

【问题讨论】:

  • 方法getCurrentTime应该返回什么?您是否希望它以 12 小时格式返回时间,而不考虑用户的区域设置?
  • 我需要以 NSDate 时间格式获取当前时间,例如 (1999-12-31 18:54:30 +0000)。之后,我将计算两个 NSDate 之间的 timeIntervalSinceDate。这里 getCurrentTime 在 NSString 中返回格式化的当前时间(例如:11:09:14 PM)。
  • 我仍然不确定您要达到的目标。 checkTimeFormat 应该怎么做?
  • 我只需要显示倒计时。请给我建议。
  • 首先,我们需要一些您正在转换的时间字符串的示例。其次,如果您发现您有一个 24 小时格式字符串,您应该简单地将日期格式化程序设置为该格式,而不是尝试将 24 转换为 12。第三,如果您使用 12 小时格式,您应该始终将语言环境设置为一个“安全的”,例如 en_US_POSIX。

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

你可以试试:

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];

【讨论】:

  • 请给出我的问题的解决方案。 NSString 到 NSDate 返回空值..
  • 抱歉,我想你想要一个倒数计时器。我已经编辑了我的回复。
猜你喜欢
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
相关资源
最近更新 更多