calebmanley calebmanley - 2 months ago 10
Swift Question

What does the Quarter Component in Calender.Component do? (Swift)

I am trying to use yearly quarters in my iOS application but have found that the

.quarter
component does nothing. There is also no documentation I could find on it.

Calling
print(Calendar.current.date(byAdding: .quarter, value: 1, to: Date()))
just prints the current date. I would have expected it to add 3 months on to it?

Answer

You'd think that wouldn't you — but no, it appears something is broken.

A quick test in a Playground shows it all works until you use a .quarter:

//: Playground - noun: a place where people can play

import UIKit

let result = Calendar.current.date(byAdding: .quarter, value: 1, to: Date())

print (result)

let calendar1 = Calendar.current
let now1 = Date()
let newDate1 = calendar1.date(byAdding: .minute, value: 1, to: now1)
let newDate2 = calendar1.date(byAdding: .hour, value: 1, to: now1)
let newDate3 = calendar1.date(byAdding: .day, value: 1, to: now1)
let newDate4 = calendar1.date(byAdding: .month, value: 1, to: now1)
let newDate5 = calendar1.date(byAdding: .month, value: 3, to: now1)
let newDate6 = calendar1.date(byAdding: .quarter, value: 1, to: now1)

Results in:

"Sep 27, 2016, 3:30 PM"

"Optional(2016-09-27 05:30:03 +0000)\n"

gregorian (current)
"Sep 27, 2016, 3:30 PM"
"Sep 27, 2016, 3:31 PM"
"Sep 27, 2016, 4:30 PM"
"Sep 28, 2016, 3:30 PM"
"Oct 27, 2016, 3:30 PM"
"Dec 27, 2016, 3:30 PM"
"Sep 27, 2016, 3:30 PM"

It looks like as it stands in Xcode 8.0 (8A218a) you will have use months and a value of 3 as shown in the newDate5 line above.

Comments