为NSDate添加天数 [英] Adding days to NSDate

查看:89
本文介绍了为NSDate添加天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要添加几天的日期,我为此获得了许多代码但是没有一个代码在我下面显示的是我的代码,请有人帮我修复此问题

I want add days to a date, I got many codes for this but none of them are working for me below shown is my code,please somebody help me to fix this issue

int daysToAdd=[[appDlegateObj.selectedSkuData 
                                    objectForKey:@"Release Time"] intValue];

NSTimeInterval secondsForFollowOn=daysToAdd*24*60*60;

NSString *dateStr=[contentDic objectForKey:@"Date"];

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];

[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSDate *dateFromString=[[NSDate alloc]init];

dateFromString=[dateFormatter dateFromString:dateStr];

[dateFormatter release];

 NSDate *date=[dateFromString dateByAddingTimeInterval:secondsForFollowOn];


推荐答案

// Initialize stringified date presentation
NSString *myStringDate = @"2011-11-17";

// How much day to add
int addDaysCount = 30;

// Creating and configuring date formatter instance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

// Retrieve NSDate instance from stringified date presentation
NSDate *dateFromString = [dateFormatter dateFromString:myStringDate];

// Create and initialize date component instance
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:addDaysCount];

// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar] 
                              dateByAddingComponents:dateComponents 
                                              toDate:dateFromString options:0];

NSLog(@"Original date: %@", [dateFormatter stringFromDate:dateFromString]);
NSLog(@"New date: %@", [dateFormatter stringFromDate:newDate]);

// Clean up
[dateComponents release], dateComponents = nil;
[dateFormatter release], dateFormatter = nil;

输出:

Original date: 2011-11-17
New date: 2011-12-17

这篇关于为NSDate添加天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆