NSDate/NSDateFormatter - Storing only time, not date?

前端 未结 4 1677
谎友^
谎友^ 2021-02-20 05:44

I\'ve been looking around but I haven\'t seen anything that addresses this so I\'m hoping someone can help clear this up for me. What I am trying to do is use an NSDate variable

4条回答
  •  面向向阳花
    2021-02-20 06:14

    After setting the locale and the date format you should be able to convert from date to string and back. Because you just need the time, you can ignore the date part.

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[[[NSLocale alloc] 
                     initWithLocaleIdentifier:@"en_US"] autorelease]];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSString *etaStr = @"00:14:00";
    NSDate *generatedDate = [formatter dateFromString:etaStr];
    NSLog(@"%@", [formatter stringFromDate:generatedDate]);
    [formatter release];
    

    Output

    00:14:00
    

    Swift version

    Time to update this answer for swift:

    var formatter = NSDateFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    formatter.dateFormat = "HH:mm:ss"
    let etaString = "00:14:00"
    let generatedDate = formatter.dateFromString(etaString)!
    let generatedString = formatter.stringFromDate(generatedDate)
    println(generatedString)
    

    Swift 3 version

    var formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US")
    formatter.dateFormat = "HH:mm:ss"
    let etaString = "00:14:00"
    let generatedDate = formatter.date(from: etaString)!
    let generatedString = formatter.string(from: generatedDate)
    print(generatedString)
    

提交回复
热议问题