IOS NSDate from string with time only

有些话、适合烂在心里 提交于 2019-12-11 03:48:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!