NSDateFormatter wrong string after formatting

后端 未结 4 1695
独厮守ぢ
独厮守ぢ 2020-12-22 00:55

I receive a date through a string parameter, which is tempDateString, in a [day month year] format (for ex. 01 05 2005):

 NSLog(@\"tempdatestring %@\", tempD         


        
4条回答
  •  無奈伤痛
    2020-12-22 01:18

    NSDateFormatter *form = [[NSDateFormatter alloc] init];
    [form setDateFormat:@"dd MM yyyy"];
    form.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:-7200.0];
    NSDate *dayDate = [form dateFromString:@"05 10 2012"];
    NSLog(@"daydate %@", dayDate);
    NSString *strDate = [form stringFromDate:dayDate];
    NSLog(@"strDate %@",strDate);
    

    Change date format to @"dd MM yyyy". After this, dateFromString may still parse the wrong date (in my case it was yesterday 21-00). To avoid this I've set TimeZone in my DateFormatter:

    form.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:-7200.0];
    

    -7200.0 is my timezone, you should change this to yours ("0" sets to Greenwich). After this log looks like:

    daydate 2012-10-05 02:00:00 +0000
    strDate 05 10 2012
    

提交回复
热议问题