Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

ios - NSDateFormatter wrong string after formatting

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

 NSLog(@"tempdatestring %@", tempDateString);
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"dd MM YYYY"];
 NSDate *dayDate = [dateFormatter dateFromString:tempDateString];
 NSLog(@"daydate %@", dayDate);

My problem is, that the two logs don't match. The outputs are:

tempdatestring 04 10 2012
daydate 2011-12-24 22:00:00 +0000

What should I change at the date formatter's date format, to get the good date?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

2 Problems

  • your format is wrong it is @"dd MM yyyy" case sensitive
  • Use timezone to get the correct value[GMT value]

    NSString *tempDateString=@"04 10 2012" ;
    NSLog(@"tempdatestring %@", tempDateString);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    [dateFormatter setDateFormat:@"dd MM yyyy"];
    NSDate *dayDate = [dateFormatter dateFromString:tempDateString];
    NSLog(@"daydate %@", dayDate);
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...