Swift: dateFromInt() and intFromDate()

Updated: 20161208 to Swift 3

I needed a couple of convenience functions to convert between NSDates and YYYYMMDD integer dates. Here are examples of each function call:

let d0 = dateFromInt(20160111)
let d1 = intFromDate(Date())

Here’s the source for dateFromInt():

//: Date from Int YYYYMMDD
func dateFromInt(_ date:Int) -> Date {
    
    let year = date / 10000
    let month = date % 10000 / 100
    let day = date % 100
    
    let components = NSDateComponents()
    components.year = year
    components.month = month
    components.day = day
    
    let aDate = NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: components as DateComponents)
    
    return aDate!
}


Here’s intFromDate()

//: Date to Int YYYYMMDD
func intFromDate(_ date:Date) -> Int {
    
    let calendar = NSCalendar.current
    let components = calendar.dateComponents([.year, .month, .day], from: date)

    let year = components.year
    let month = components.month
    let day = components.day
    
    let intDate = year! * 10000 + month! * 100 + day!
    return intDate
    
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s