简体   繁体   中英

NSDate/NSDateFormatter - Storing only time, not date?

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(in core data) to store a time, not date and time, but just time in the format HH:MM:SS;

After looking at the NSDateFormatter class reference and the sample code provided I was able to tweak it and think that my code should look something like the following:

NSDateFormatter *timeOfArrival = [[NSDateFormatter alloc] init];
[timeOfArrival setTimeStyle:NSDateFormatterLongStyle];
[timeOfArrival setDateStyle:NSDateFormatterNoStyle];
[timeOfArrival setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];

NSString *etaStr = [attributeDict objectForKey:@"cumulativeTime"];
NSLog(@"%@", etaStr);
checkpoint.eta = [timeOfArrival dateFromString:etaStr];

Everything up until the last line where I try to create my NSDate object from my string works, but after that, checkpoint.eta is still nil.

etaStr correctly outputs my expected value, 00:14:00, for example, but I'm not sure what I'm doing wrong.

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)

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.

Swift 4 If you want to use time with today's date

let todate = Date()
        let formater = DateFormatter()
        formater.dateFormat = "yyyy:MM:dd"
       let date = formater.string(from: todate)
        print(date)
        let completeDate = date + ":9:00AM"
        print(completeDate)
        let anotherFormater = DateFormatter()
        anotherFormater.dateFormat = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ"
       anotherFormater.date(from: completeDate)

if you want to add time in any date then:-

  let completeDate = "2019-02-15" + ":9:00AM"
            print(completeDate)
            let anotherFormater = DateFormatter()
            anotherFormater.dateFormat = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ"
           anotherFormater.date(from: completeDate)

I ended up not using NSDate/NSDateFormatter because I couldn't get it to work properly. My solution consisted of parsing my time string into a hours, minutes, and seconds. I eventually ended up converting everything to seconds, and storing them in that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM