Get day of week using NSDate
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
}
}
How to find weekday from today's date using NSDate?
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [comp weekday]; // 1 = Sunday, 2 = Monday, etc.
See @HuguesBR's answer if you just need the weekday without other components (requires iOS 8+).
NSInteger weekday = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday
fromDate:[NSDate date]];
(If you don't get a correct answer, check if you have mistyped NSCalendarUnitWeekday
with other week-related components like NSCalendarUnitWeekdayOrdinal
, etc.)
Swift 3:
let weekday = Calendar.current.component(.weekday, from: Date())
// 1 = Sunday, 2 = Monday, etc.
How to get Day number of week from NSDate
It will fetch you the day number i.e. 2. The day number are always same for every week. (1-7).
As pointed by Vyachaslav Gerchicov, the weekday number starts from Sunday
i.e Sunday is 1, Monday is 2... Saturday is 7
//Assuming your calendar is initiated like this
NSCalendar *_calendar = [NSCalendar currentCalendar];
//Fetch the day number
NSInteger day = [_calendar component:NSCalendarUnitWeekday fromDate:date];
Explore NSCalendar
for more details here
For Swift 5.x
let day = Calendar.current.component(.weekday, from: date)
Explore Calendar
for more details here
Objective C - How can i get the weekday from NSDate?
Edit for Mac:
The format of the string has to be —YYYY-MM-DD HH:MM:SS ±HHMM according to the docs, all fields mandatory
Old answer (for iPhone and tested on simulator):
There is no (public) -initWithString:
method in NSDate
, and what you get returned is not what you expect.
Use a properly configured (you need to give the input format) NSDateFormatter
and -dateFromString:
.
How do I get the day of the week with Foundation?
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
outputs current day of week as a string in locale dependent on current regional settings.
To get just a week day number you must use NSCalendar class:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];
How do I get weekday and/or name of month from a NSDate variable?
There is no need to manually convert to the Swedish words. iPhone will do it for you. Try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyyMMdd";
NSDate *date = [dateFormatter dateFromString:@"20111010"];
// set swedish locale
dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"];
dateFormatter.dateFormat=@"MMMM";
NSString *monthString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"month: %@", monthString);
dateFormatter.dateFormat=@"EEEE";
NSString *dayString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"day: %@", dayString);
Output:
month: Oktober
day: Måndag
How can I check for a specific day of the week using NSDate in Swift?
This is how I would accomplish the task.
var CurrentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone()
dateFormatter.dateFormat = "ccc"
let Monday = dateFormatter.stringFromDate(CurrentDate)
let isMonday = "Mon"
if Monday == isMonday {
print("It's Monday")
}
else {
let otherDay = dateFormatter.stringFromDate(CurrentDate)
print(otherDay)
}
Get Weekday from Date - Swift 3
Presumably you have a Date
already?
let weekday = Calendar.current.component(.weekday, from: myDate)
Maybe you want the name of the weekday?
let f = DateFormatter()
f.weekdaySymbols[Calendar.current.component(.weekday, from: Date()) - 1]
The -1
is added at the end because Calendar.current.component(.weekday, from: Date()) returns values from 1-7 but weekdaySymbols expects array indices.
Investigate the NSCalendar
/DateComponents
api or edit your question to be more specific if you need help with the DateComponents api.
Get first day of week and last day in objective-c
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
cal.firstWeekday = 2;// set first week day to Monday
// 1: Sunday, 2: Monday, ..., 7:Saturday
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSCalendarUnitWeekOfYear
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfTheWeek holds the beginning of the week
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval - 1];
// endOfWeek now holds the last second of the last week day
[cal rangeOfUnit:NSCalendarUnitDay
startDate:&endOfWeek
interval:NULL
forDate:endOfWeek];
// endOfWeek now holds the beginning of the last week day
testing:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
NSLog(@"start: %@", [formatter stringFromDate:startOfTheWeek]);
NSLog(@"end: %@", [formatter stringFromDate:endOfWeek]);
prints
start: 12.10.15, 00:00
end: 18.10.15, 00:00
So Monday is the beginning of the week
if I set
cal.firstWeekday = 1;
it will print
start: 11.10.15, 00:00
end: 17.10.15, 00:00
Sunday is the first day of the week
Related Topics
What Is an Optional Value in Swift
Get Nth Character of a String in Swift Programming Language
Read and Write a String from Text File
Firestore: How to Get Random Documents in a Collection
Round Trip Swift Number Types To/From Data
Getting "File Not Found" in Bridging Header When Importing Objective-C Frameworks into Swift Project
How to Get the Name of Enumeration Value in Swift
Can Swift Convert a Class/Struct Data into Dictionary
Can You Execute an Applescript Script from a Swift Application
Main Thread Checker: Ui API Called on a Background Thread: -[Uiapplication Applicationstate]
Why Are Emoji Characters Like 👩👩👧👦 Treated So Strangely in Swift Strings
What Is a Good Example to Differentiate Between Fileprivate and Private in Swift3
Realitykit VS Scenekit VS Metal - High-Quality Rendering
How to Set Layer Cornerradius For Only Bottom-Left, Bottom-Right, and Top-Left Corner