Skip to content

Instantly share code, notes, and snippets.

@anirudhamahale
Last active July 19, 2017 05:23
Show Gist options
  • Save anirudhamahale/84a95159ec2cc164ed0e924eff9feac9 to your computer and use it in GitHub Desktop.
Save anirudhamahale/84a95159ec2cc164ed0e924eff9feac9 to your computer and use it in GitHub Desktop.
Better way to manage the date.
func dateOutOf(Iso8601 date: String) -> Date {
let dateFormatter = DateFormatter()
// dateFormatter.calendar = Calendar(identifier: .iso8601)
// dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSz" //Your date format
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) //Current time zone
let date = dateFormatter.date(from: date) //according to date format your date string
return date! //Convert String to Date
}
let date = "2017-07-11T10:52:36.577Z"
// March 21, 2017 17:19 IST
func returnDateForTheNews(date: String) -> String {
let months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "Octomber", "November", "December"]
let tempDate = dateOutOf(Iso8601: date)
var componentsToAdd = DateComponents()
componentsToAdd.hour = 5
componentsToAdd.minute = 30
let calender = Calendar.current
let date5 = calender.date(byAdding: componentsToAdd, to: tempDate)
let components = calender.dateComponents([.month, .day, .hour, .minute, .year], from: tempDate)
return "\(months[components.month!]) \(components.day!), \(components.year!) \(components.hour!):\(components.minute!) IST"
}
let toPrint = returnDateForTheNews(date: date)
print(toPrint)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment