NSDate/NSDateFormatter - Storing only time, not date?

前端 未结 4 1618
谎友^
谎友^ 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:01

    After thinking this through a bit, and trying Mundi's answer, it looked like Mundi was creating a string from a string without creating an NSDate or converting to or from an NSDate. I needed to store an NSDate as well, so here's how you can get what you want fairly easily:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
    NSDate *eventDate = [dateFormat dateFromString:[attributeDict objectForKey:@"cumulativeTime"]];
    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [timeFormat setDateFormat:@"HH:mm:ss a"];
    NSString *timeString = [timeFormat stringFromDate:eventDate];
    NSLog(@"EventDate: %@",timeString);
    

    Mundi's answer works, so someone should upvote his answer since I down voted too fast without taking into account that leaving off the date @"1/21/13 00:14:00" doesn't really matter in this case, but he should have put a date in front of it to make it clear that the date isn't output. Someone's variable from a web service or some other object would have the date, then the @"HH:mm:ss a" would pull out the time only. This also helps those who need the AM/PM on their date or time.

提交回复
热议问题