I created a method that is supposed to take in a string in "YYYY-MM-DD" form and spit out an int that represents the dates position in relation to the week it is in (regardless if it overlaps between months). So e.g sunday=1 monday=2 and so on.
Here is my code:
func getDayOfWeek(today:String)->Int{
var formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-DD"
var todayDate:NSDate = formatter.dateFromString(today)!
var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: todayDate)
var weekDay = myComponents.weekdayOrdinal
return weekDay
}
I know that NSCalendarUnit.WeekdayOrdinalCalendar
is wrong but I have tried I think most logical combinations. And have also messed around with myComponents.weekdayOrdinal
e.g used mycomponents.day
or .weekday
.
Here are my options in what to use:
static var EraCalendarUnit: NSCalendarUnit { get }
static var YearCalendarUnit: NSCalendarUnit { get }
static var MonthCalendarUnit: NSCalendarUnit { get }
static var DayCalendarUnit: NSCalendarUnit { get }
static var HourCalendarUnit: NSCalendarUnit { get }
static var MinuteCalendarUnit: NSCalendarUnit { get }
static var SecondCalendarUnit: NSCalendarUnit { get }
static var WeekCalendarUnit: NSCalendarUnit { get }
static var WeekdayCalendarUnit: NSCalendarUnit { get }
static var WeekdayOrdinalCalendarUnit: NSCalendarUnit { get }
static var QuarterCalendarUnit: NSCalendarUnit { get }
static var WeekOfMonthCalendarUnit: NSCalendarUnit { get }
static var WeekOfYearCalendarUnit: NSCalendarUnit { get }
static var YearForWeekOfYearCalendarUnit: NSCalendarUnit { get }
static var CalendarCalendarUnit: NSCalendarUnit { get }
static var TimeZoneCalendarUnit: NSCalendarUnit { get }
It is not clear to me since there is no DayOfWeekUnit option (or something similar).
If you display a date with print(Date()) you'll get output like 2018-11-17 23:38:02 +0000 (The +0000 bit is the offset from UTC.
Use the DateTime. DayOfWeek or DateTimeOffset. DayOfWeek property to retrieve a DayOfWeek value that indicates the day of the week. If necessary, cast (in C#) or convert (in Visual Basic) the DayOfWeek value to an integer.
Retrieving the day of the week's number is dramatically simplified in Swift 3 because DateComponents
is no longer optional. Here it is as an extension:
extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}
// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
print(Date().dayNumberOfWeek()!) // 4
If you were looking for the written, localized version of the day of week:
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or use capitalized(with: locale) if you want
}
}
print(Date().dayOfWeek()!) // Wednesday
What you are looking for (if I understand the question correctly) is NSCalendarUnit.CalendarUnitWeekday
. The corresponding property of NSDateComponents
is weekday
.
Note also that your date format is wrong (the full specification can be found here: http://unicode.org/reports/tr35/tr35-6.html).
The function can be simplified slightly, using automatic type inference, also you use variables a lot where constants are sufficient.
In addition, the function should return an optional which is nil
for an invalid input string.
Updated code for Swift 3 and later:
func getDayOfWeek(_ today:String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
}
Example:
if let weekday = getDayOfWeek("2014-08-27") {
print(weekday)
} else {
print("bad input")
}
Original answer for Swift 2:
func getDayOfWeek(today:String)->Int? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
if let todayDate = formatter.dateFromString(today) {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
let weekDay = myComponents.weekday
return weekDay
} else {
return nil
}
}
If you want the full "Sunday", "Monday", "Tuesday", "Wednesday" etc.
EDIT: There's actually a built in format that returns localized day names:
extension NSDate {
func dayOfTheWeek() -> String? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(self)
}
}
My previous solution (for English only):
extension NSDate {
func dayOfTheWeek() -> String? {
let weekdays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]
let calendar: NSCalendar = NSCalendar.currentCalendar()
let components: NSDateComponents = calendar.components(.Weekday, fromDate: self)
return weekdays[components.weekday - 1]
}
}
You don't need to unwrap calendar and components, they are guaranteed by the foundation framework.
Usage:
print(myDate.dayOfTheWeek())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With