Change year, month and day of NSDate object

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


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]];

Read more on my blog https://github.com/onmyway133/blog/issues/54

Today I'm trying to change the year of a Date object to 2000 in Swift.

let date = Date()

Firstly, I tried with date(bySetting:) but it does not work with past year. It simply returns nil

Calendar.current.date(bySetting: .year, value: 2000, of: date)

Secondly, I tried with dateComponents. The component.year has changed, but it calendar still returns the original date, very strange !!. No matter what timezone and calendar I use, it still has this problem

var component = calendar.dateComponents(in: TimeZone.current, from: base)
component.year = year
Calendar.current.date(from: component)

Finally, I tried to be more explicit, and it works 🎉

var component = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: base)
component.year = year
Calendar.current.date(from: component)

Tags:

Ios

Iphone