我可以通过使用子串断开字符串来实现这一点,但应该有一些方法来解析特定格式的字符串并获得所需的值。
如果还有其他简单而优雅的方法,请帮助我。
[更新] 这就是我使用子串的方式:
NSRange ptRange = [timeString rangeOfString:@"T"];
NSRange hRange = [timeString rangeOfString:@"H"];
NSRange mRange = [timeString rangeOfString:@"M"];
NSString *hours = nil;
if (hRange.location != NSNotFound) {
hours = [timeString substringWithRange:NSMakeRange(ptRange.location+ptRange.length, hRange.location-(ptRange.location+ptRange.length))];
}
else {
hRange = ptRange;
}
NSString *minutes = nil;
if (mRange.location != NSNotFound) {
minutes = [timeString substringWithRange:NSMakeRange(hRange.location+hRange.length, mRange.location-(hRange.location+hRange.length))];
}
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm"];
NSDate*date = [df dateFromString:[NSString stringWithFormat:@"%d:%d",hours.integerValue,minutes.integerValue]];
答案 0 :(得分:0)
截至目前,我的实施是这个问题的答案
NSRange ptRange = [timeString rangeOfString:@"T"];
NSRange hRange = [timeString rangeOfString:@"H"];
NSRange mRange = [timeString rangeOfString:@"M"];
NSString *hours = nil;
if (hRange.location != NSNotFound) {
hours = [timeString substringWithRange:NSMakeRange(ptRange.location+ptRange.length, hRange.location-(ptRange.location+ptRange.length))];
}
else {
hRange = ptRange;
}
NSString *minutes = nil;
if (mRange.location != NSNotFound) {
minutes = [timeString substringWithRange:NSMakeRange(hRange.location+hRange.length, mRange.location-(hRange.location+hRange.length))];
}
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm"];
NSDate*date = [df dateFromString:[NSString stringWithFormat:@"%d:%d",hours.integerValue,minutes.integerValue]];