Skip to content

Instantly share code, notes, and snippets.

@justin-nodeboy
Last active February 13, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justin-nodeboy/a37495463597830bab91 to your computer and use it in GitHub Desktop.
Save justin-nodeboy/a37495463597830bab91 to your computer and use it in GitHub Desktop.
Some little Swift helper functions for dealing with dates.
//Use as follows
//let dateHelper = Helpers()
//let dateString: String = row["dateString"] as! String
//label.text = dateHelper.getFormattedDate(dateString)
import Foundation
class Helpers: NSObject {
func getFormattedDate(date: String) -> String{
let formatter = NSDateFormatter()
//Change the below format to whatever format you get from the API service you consume
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = NSLocale.currentLocale()
let date = formatter.dateFromString(date)
formatter.locale = NSLocale.currentLocale()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .NoStyle
let formattedDate = formatter.stringFromDate(date!)
return formattedDate
}
func getFormattedTime(time: String) -> String{
let formatter = NSDateFormatter()
//Change the below format to whatever format you get from the API service you consume
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = NSLocale.currentLocale()
let date = formatter.dateFromString(time)
formatter.dateStyle = .NoStyle
formatter.timeStyle = .ShortStyle
let timeString = formatter.stringFromDate(date!)
return timeString
}
func combineDateWithTime(date: String, time: String) -> NSDate? {
let formatter = NSDateFormatter()
//Change the below format to whatever format you get from the API service you consume
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = NSLocale.currentLocale()
let newDate = formatter.dateFromString(date)
let newTime = formatter.dateFromString(time)
let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components([.Year, .Month, .Day], fromDate: newDate!)
let timeComponents = calendar.components([.Hour, .Minute, .Second], fromDate: newTime!)
let mergedComponments = NSDateComponents()
mergedComponments.year = dateComponents.year
mergedComponments.month = dateComponents.month
mergedComponments.day = dateComponents.day
mergedComponments.hour = timeComponents.hour
mergedComponments.minute = timeComponents.minute
mergedComponments.second = timeComponents.second
return calendar.dateFromComponents(mergedComponments)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment