I want to get a quarter value in NSDateComponents class

It seems that there is an issue with the NSQuarterCalendarUnit being ignored (haven’t verified, but did see a bug reported). Anyway, it is simple enough to get around… Just use the NSDateFormatter class. // After your NSDate *date, add… NSDateFormatter *quarterOnly = [[NSDateFormatter alloc]init]; [quarterOnly setDateFormat:@”Q”]; int quarter = [[quarterOnly stringFromDate:date] intValue]; // Then change … Read more

Swift 3.0 : Convert server UTC time to local time and vice-versa

I don’t know what’s wrong with your code.But looks too much unnecessary things are there like you’re setting calendar, fetching some elements from string. Here is my small version of UTCToLocal and localToUTC function. But for that you need to pass string in specific format. Cause I’ve forcly unwrapped date objects. But you can use … Read more

NSDate beginning of day and end of day

Start Of Day / End Of Day — Swift 4 // Extension extension Date { var startOfDay: Date { return Calendar.current.startOfDay(for: self) } var endOfDay: Date { var components = DateComponents() components.day = 1 components.second = -1 return Calendar.current.date(byAdding: components, to: startOfDay)! } var startOfMonth: Date { let components = Calendar.current.dateComponents([.year, .month], from: startOfDay) return Calendar.current.date(from: … Read more

Calculate age from birth date using NSDateComponents in Swift

You get an error message because 0 is not a valid value for NSCalendarOptions. For “no options”, use NSCalendarOptions(0) or simply nil: let ageComponents = calendar.components(.CalendarUnitYear, fromDate: birthday, toDate: now, options: nil) let age = ageComponents.year (Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits from NilLiteralConvertible.) Update for … Read more

Differences in NSDateComponents syntax?

Swift 2 The NSCalendarUnit names have changed in Swift 2. Also, now we have to pass these arguments in an OptionSet, like this: let components = calendar.components([.Hour, .Minute, .Second, .Nanosecond], fromDate: date) Swift 3 Many things have changed, according to the Swift API Design Guidelines. Updated syntax: let date = Date() let calendar = Calendar.current() … Read more