IOS NSDate from string with time only

2019-07-18 21:32发布

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

2条回答
ら.Afraid
2楼-- · 2019-07-18 21:48

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

查看更多
Explosion°爆炸
3楼-- · 2019-07-18 22:02

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];
查看更多
登录 后发表回答