How to convert NSString to NSDate using NSDateFormatter?

限于喜欢 提交于 2020-01-24 21:35:07

问题


I getting the date from the webservice like "2012-07-03 07:26:48". I have saved in NSString after parsing from webservice. While convert the NSString to NSDate used below code,

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

    NSString *dateStr = @"2012-07-03 07:26:48";
    NSDate *date = [dateFormatter1 dateFromString:dateStr];
    NSLog(@"Date : %@", date);
   The NSLog value is "2012-07-03 01:56:48 +0000";

The NSLog value is "2012-07-03 01:56:48 +0000"; I don't know why the time has changed. Can anyone please help me to do this?


回答1:


You need to put timezone as:

theDateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

Because it is considering GMT time format.




回答2:


You have to set the time zone of the NSDateFormatter.




回答3:


By default,Date is saved in utc format while converting string to nsdate... you can get original time from date as a string..if you want to change timezone, change it using dateformatter.. otherwise dont change



来源:https://stackoverflow.com/questions/11396609/how-to-convert-nsstring-to-nsdate-using-nsdateformatter

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