简体   繁体   中英

iOS NSDate from string with time only

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... :)

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];

You didn't pass any information beside the time. Any other values in your NSDate are therefore undefined.

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