nsdate - Number to Date - Swift -
getting day of year straightforward, e.g.
func dayofyear(inputdate:nsdate) -> (int) { let cal = nscalendar.currentcalendar() let returnday = cal.ordinalityofunit(.calendarunitday, inunit: .calendarunityear, fordate: inputdate) return returnday }
but how do reverse? return day/month. can write tedious routine back-calculating there smart way?
yes, nscalendar
provides way coalesce calendar components single date object. take @ example wrote in playground:
import uikit import foundation let inputdate: nsdate = nsdate() let calendar = nscalendar.currentcalendar() let day = calendar.ordinalityofunit(.calendarunitday, inunit: .calendarunityear, fordate: inputdate) let components = nsdatecomponents() components.day = day let date = calendar.datefromcomponents(components)
according documentation,
when there insufficient components provided specify absolute time, calendar uses default values of choice. when there inconsistent information, calendar may ignore of components parameters or method may return nil. unnecessary components ignored (for example, day takes precedence on weekday , weekday ordinals).
furthermore,
note computations can take relatively long time perform.
see nscalendar class reference more information.
Comments
Post a Comment