Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change year, month and day of NSDate object

Tags:

ios

iphone

in my iPhone application I have a start date of event, for exemple: 2013-05-17 15:00:12 +0000. My question is, how can I change 2013-05-17 with today date, but leave time the same?

like image 556
revolutionkpi Avatar asked Jun 13 '13 10:06

revolutionkpi


2 Answers

You need to gather the date components and amend the required properties.

//gather current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];

//gather date components from date
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:[NSDate date]];

//set date components
[dateComponents setDay:17];
[dateComponents setMonth:5];
[dateComponents setYear:2013];

//save date relative from date
NSDate *date = [calendar dateFromComponents:dateComponents];

Either that, or you could add the number of seconds in 1 day to increment the value:

NSDate *date = [NSDate dateWithTimeInterval:((60 * 60) * 24) sinceDate:[NSDate date]];
like image 190
Zack Brown Avatar answered Nov 20 '22 19:11

Zack Brown


Swift 3 & IOS 10.2

    let calendar = Calendar.current

    var dateComponents: DateComponents? = calendar.dateComponents([.hour, .minute, .second], from: Date())

    dateComponents?.day = 17
    dateComponents?.month = 5
    dateComponents?.year = 2013

    let date: Date? = calendar.date(from: dateComponents!)
    print(date!)

Swift 3 & IOS 10.2

like image 12
ramchandra n Avatar answered Nov 20 '22 19:11

ramchandra n