将多分钟数字(超过2分钟)转换为NSDate

时间:2016-03-31 06:24:17

标签: ios objective-c nsdateformatter nsregularexpression

我正在尝试解析由多个分钟组成的时钟字符串,并使用NSDate将其转换为NSDateFormatter

我尝试解析的字符串示例是@"1234:56",其中1234是时钟的分钟数,56秒是秒。我尝试使用@"mmmm:ss"这样的格式,但它返回了nil。

如果有可能,有人可以帮我吗?

由于

4 个答案:

答案 0 :(得分:1)

NSDateFormatter仅适用于合法的日期格式且没有'mmmm'。您应该自己约会:

NSString *str = @"234:56";
NSArray<NSString *> *components = [str componentsSeparatedByString:@":"];
NSInteger minute = 0;
NSInteger second = 0;
switch (components.count) {
    case 1:
        second = components[0].integerValue;
        break;
    case 2:
        second = components[0].integerValue;
        minute = components[1].integerValue;
        break;

    default:
        break;
}
// then convert to hours.

答案 1 :(得分:1)

我不确定你想做什么,但我建议你这样做:

NSArray *timeArray = [@"1234:56" componentsSeparatedByString:@":"];
NSUInteger minutes = [[timeArray firstObject] integerValue];
NSUInteger seconds = [[timeArray lastObject] integerValue];

NSTimeInterval totalSeconds = minutes*60+seconds;

然后你应该创建一个新的日期对象并使用它。

NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:totalSeconds];

答案 2 :(得分:0)

试试这个。

NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timerLabel.text = timeString;

答案 3 :(得分:0)

如果你想将其转换为HH:mm:ss,那么我的方法将是:

// assuming you wouldn't have any hours in the string and format will always be minutes:seconds 

 NSArray *timeArray = [@"1234:56" componentsSeparatedByString:@":"]; 

 //array's firstObject will be the "minutes/Hours"
 NSString *minutesAndHours = [timeArray firstObject];
 int hours = [minutesAndHours intValue]/60;
 int minutes = [minutesAndHours intValue]%60;
 int seconds = [timeArray lastObject];

//create the format

NSString *time = [NSString stringWithFormat:@"%d:%d:%d",hours,minutes,seconds];

//then use the time format
NSString *time = [NSString stringWithFormat:@"%d:%d:%d",hours,minutes,seconds];
NSDateFormatter *format = [NSDateFormatter new];
[format setDateFormat:@"HH:mm:ss"];
NSDate *date = [format dateFromString:time];

类似这样的事情