问题
My task is to parse string with time to NSDate. And I do it very well with following code:
NSString* timeStr = @"15:00:00"
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate* result = [formatter dateFromString:timeStr];
But as a result I get 2000-01-01 15:00:00 CET and I dont understand why date was set to 2000-01-01, not 2001-01-01 (which is reference date) or 1970-01-01. And 2000-01-01 seems to be not random value... :)
回答1:
If you want it's just a string with the date part, simply use a dateFormatter, similar what you've done before.
NSString* timeStr = @"15:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate* result = [formatter dateFromString:timeStr];
[formatter setDateFormat:@"YYYY-MM-DD"];
timeStr = [formatter stringFromDate:result];
Or you need to set date string in date formatter directly, this is because if you specify time string in date formatter you will get combination of date with time string
NSString* dateStr = @"2001-01-01";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[formatter setDateFormat:@"YYYY-MM-DD"];
NSDate* result = [formatter dateFromString:dateStr];
回答2:
You didn't pass any information beside the time. Any other values in your NSDate are therefore undefined.
来源:https://stackoverflow.com/questions/25051915/ios-nsdate-from-string-with-time-only