Can't convert from NSString to NSDate

前端 未结 2 903
孤街浪徒
孤街浪徒 2021-01-27 08:33

I can\'t convert my NSString to NSDate. here\'s the code:

+ (NSDate *) stringToNSDate: (NSString *) dateString{
[NSDateFormatter setDefaultFormatterBehavior:NSDa         


        
相关标签:
2条回答
  • 2021-01-27 09:02

    From the information you've given, the problem appears to be that your dateString separates the date components with slashes (\), but your date formatter is expecting dashes (-).


    Edit

    To answer your other question, you can use stringByReplacingOccurrencesOfString:withString:.

    For example:

    NSString *date1 = @"2012/12/10 ...";
    NSString *date2 = [date1 stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    

    Note that this will replace every / with -, so just be careful about timezones etc.

    0 讨论(0)
  • 2021-01-27 09:11

    Try this instead:

    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss ZZZ"];
    
    0 讨论(0)
提交回复
热议问题