Created
April 15, 2015 13:56
-
-
Save garkhipov/1ef52be2467baff68aa4 to your computer and use it in GitHub Desktop.
NSDateFormatter and NSDateComponentsFormatter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let locale = NSLocale(localeIdentifier: "ru_RU") | |
let dateFormatter = NSDateFormatter() | |
dateFormatter.timeStyle = .ShortStyle | |
dateFormatter.dateStyle = .MediumStyle | |
dateFormatter.locale = locale | |
dateFormatter.doesRelativeDateFormatting = true | |
dateFormatter.formattingContext = NSFormattingContext.MiddleOfSentence | |
let calendar = NSCalendar.autoupdatingCurrentCalendar() | |
calendar.locale = locale | |
let units: NSCalendarUnit = | |
NSCalendarUnit.CalendarUnitYear | |
| NSCalendarUnit.CalendarUnitMonth | |
| NSCalendarUnit.CalendarUnitDay | |
| NSCalendarUnit.CalendarUnitHour | |
| NSCalendarUnit.CalendarUnitMinute | |
| NSCalendarUnit.CalendarUnitSecond | |
let dcFormatter = NSDateComponentsFormatter() | |
dcFormatter.calendar = calendar | |
dcFormatter.unitsStyle = .Full | |
dcFormatter.maximumUnitCount = 1 | |
dcFormatter.allowedUnits = units | |
// Change this value to play around | |
let interval: NSTimeInterval = 1*3600*24 | |
let date = NSDate(timeIntervalSinceNow: interval) | |
let components = calendar.components(units, fromDate: NSDate(), toDate: date, options:nil) | |
// Possible outputs: | |
dateFormatter.stringFromDate(date) | |
dcFormatter.stringFromDate(NSDate(), toDate: date) | |
dcFormatter.stringFromTimeInterval(interval) | |
dcFormatter.stringFromDateComponents(components) | |
NSDateComponentsFormatter.localizedStringFromDateComponents(components, unitsStyle: .Full) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment