2 exit door eXit_door 于 2013.07.24 14:46 提问

转换NSString到NSDate

从数据库中获取NSString后,需要添加日期,比如添加10//12/15/45/60。怎么实现?

NSString *expiryDateStr = [NSString stringWithFormat:@"%@",[[assets valueForKeyPath:@"assetrewards.expirydate"] objectAtIndex:0]];
        NSLog(@" date %@",expiryDateStr);    
        //DATE FORMATTER
        NSDateFormatter *dateFormat = [ [NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd/MM/yyyy"];
        NSDate *_date = [dateFormat dateFromString:expiryDateStr];
       [dateFormat setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]];
        [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:3600*5]];
        NSLog(@"date format %@",dateFormat);
        NSLog(@"Date: %@", _date);

获得输出结果:

date 07/10/2013
date format <NSDateFormatter: 0x9f9d4a0>
Date: 2013-10-06 18:30:00 +0000

日期变了,不知道哪出错了,如果是正确日期,应该怎么添加日子?

2个回答

xinyoulingxi1_tong
xinyoulingxi1_tong   2013.07.24 15:30
NSString *expiryDateStr = @"07/10/2013";

NSLog(@" date %@",expiryDateStr);

expiryDateStr=[expiryDateStr stringByAppendingString:@" 00:00:00 +000"];
//DATE FORMATTER

NSDateFormatter *dateFormat = [ [NSDateFormatter alloc] init];   
[dateFormat setDateFormat:@"dd/MM/yyyy HH:mm:ss Z"];
NSDate *_date = [dateFormat dateFromString:expiryDateStr];
[dateFormat setDateFormat:[NSString stringWithFormat:@"dd MMM yyyy HH:mm"]];
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDateComponents *components = [[NSCalendar currentCalendar] 
components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit fromDate:_date];
NSInteger day = [components day]+1; // U can add as per your requirement


[components setDay:day];
NSDate *NextDate = [[NSCalendar currentCalendar] dateFromComponents:components];

NSLog(@"Next Date: %@", NextDate);
SUNVIV
SUNVIV   2016.05.20 16:27

日期变了是因为时区问题,字符串转成时间会早8小时。

Csdn user default icon
上传中...
上传图片
插入图片