I have a date that I need to split in some components. for example
let components = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour
let date = calendar.components(components, fromDate: aDate, toDate: NSDate(), options: nil)
var dateToPrint = "\(date.day) days \(date.hour) hours"
dateToPrint will be the number of days and hours from aDate to now. But if i want the number of weeks instead of days
let components = NSCalendarUnit.CalendarUnitWeek | NSCalendarUnit.CalendarUnitHour
let date = calendar.components(components, fromDate: aDate, toDate: NSDate(), options: nil)
var dateToPrint = "\(date.week) weeks \(date.hour) hours"
date.week does not exist. So how I could resolve this?
Not sure which you want, but there are
weekday
,weekdayOrdinal
,weekOfMonth
andweekOfYear
. (week
has been deprecated.)I liked the API in Leo's solution and used it. However I ran into problem when I ran it (Jun 13, 2015 9:33 AM PST). The symptoms were:
When the date is in the future, xFromToday function were returning results for -(t-delta) (for example for 1 month in the future the XFromToday functions would return (0, -4, -29, -719, -43199) for x=(month,week,days, hrs, mins) . The relativeDates string would return "1 weeks from today"
When the date is in the past, the results would be for -t, except for relative date string. For example, for one month in the past, I would get (1, 4, 31, 744, 44640). Relative date string was: "4 weeks and 744 hrs"
I cannot paste the test output due to confidentiality, but the code with NSDate.test() is pasted. It also has few other stuff borrowed from another post (quoted in code) and some formatting stuff I wrote.
Here is the "fix" I did. I have added a santizedDates() function that returns "from" and "to" dates , and a sign multiplier (+1/-1). A 1-minute offset is added to date span if the comparison was in the future . It works for the test case. Also produces correct and human readable output from relativeDateString(capitalizeFirst:Bool=false) such as: "today, 1 hour 1 minute in the past" . I have posted a question as to why this behavior happens in the first place here:
NSCalendar.components().minute returning inconsistent values
You're going to need to make another variable called "calendar" (NSCalendar object) and using the init "currentCalendar" method. Once you have the calendar object defined, call the method under calendar rangeOfUnit:NSWeekCalendarUnit inUnit:NSMonthCalendarUnit forDate:date. Then make a NSInteger called amountOfWeeks equal to the range the above function returns. The length of the range the function returns will be the number of weeks in that month.
Xcode 8.3.2 • Swift 3.1