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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -