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 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.
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
}
}
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 to get the day name from a selected date in swift?]
To get the weekday do the following:
let dateFormatter = DateFormatter()
var weekday: String = ""
dateFormatter.dateFormat = "cccc"
weekday = dateFormatter.string(from: date)
Read more about the different formats here:
http://userguide.icu-project.org/formatparse/datetime
Find weekday of a date given the month start weekday
It is hard to use modular arithmetic if you don't start counting from zero.
So let's define some new variables:
W = X - 1 = the weekday number, where W = 0 means Sunday
D = Y - 1 = the day of the month, starting with 0
Then W + D is the weekday number (Sunday = 0) of day D, if W + D < 7.
So take (W + D) mod 7 to get the weekday number of day D. Add 1 to convert back to Sunday = 1, so ((W + D) mod 7) + 1.
Substitute the definitions of W and D.
Weekday number of day X (where Sunday = 1) = ((X - 1 + Y - 1) mod 7) + 1 = ((X + Y - 2) mod 7) + 1.
How do I get the name of a day of the week in the user's locale?
An NSDateFormatter
can give you the list of names:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setLocale: [NSLocale currentLocale]];
NSArray * weekdays = [df weekdaySymbols];
Which you can then index like any other array [weekdays objectAtIndex:dayIdx];
Be aware, however, that the first weekday may differ by locale; exactly how it may vary (along with many other things about NSCalendar
) is not particularly well-explained in the docs.
How to extract today, yesterday from Date() and make it localised like weekday and months?
DateFormatter
has special flag for that: doesRelativeDateFormatting
, which renders dates in relative format, using locale set for this formatter.
… If a date formatter uses relative date formatting, where possible it
replaces the date component of its output with a phrase—such as
“today” or “tomorrow”—that indicates a relative date. The available
phrases depend on the locale for the date formatter; whereas, for
dates in the future, English may only allow “tomorrow,” French may
allow “the day after the day after tomorrow,” …
Example:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent // Using system locale
dateFormatter.doesRelativeDateFormatting = true // Enabling relative date formatting
// other dataFormatter settings here, irrelevant for example
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
let now = Date()
let dateString: String = dateFormatter.string(from: now)
print("dateString: \(dateString)") // Prints `dateString: <Today in current locale>`
Related Topics
Is There a Public API for Card View UI That Can Be Seen Across iOS 10
Uicollectionview Horizontal Paging - How to Use Flow Layout
Swift: Declare an Empty Dictionary
Uiimageview Aspect Fit and Center
Macos on Vmware Doesn't Recognize iOS Device
Change Uitextfield and Uitextview Cursor/Caret Color
How to Pop Two Views at Once from a Navigation Controller
How to Set Image as a Title to Uinavigationbar
Uicollectionview with a Sticky Header
How to Make Uibutton's Text Alignment Center? Using Ib
Drawrect Circle and Animate Size/Color
iOS App, Programmatically Get Build Version
How to Show Uipickerview When Selecting Uitextfield
Tableview Rounded Corners and Shadow
Core Bluetooth - Constant Rssi Updates of In-Range Devices
iOS - Return to Safari from Native App Without Opening New Tab
How to Make Cmake Use Specific Compiler and Flags When Final Compilation Stage Instead of Detection