How do I get the day of the week as a string?
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];
Just use these three lines:
CFAbsoluteTime at = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef tz = CFTimeZoneCopySystem();
SInt32 WeekdayNumber = CFAbsoluteTimeGetDayOfWeek(at, tz);
Many of the answers here are deprecated. This works as of iOS 8.4 and gives you the day of the week as a string and as a number.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"The day of the week: %#", [dateFormatter stringFromDate:[NSDate date]]);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [gregorian components:NSCalendarUnitWeekday fromDate:[NSDate date]];
int weekday = [comps weekday];
NSLog(#"The week day number: %d", weekday);
Here's how you do it in Swift 3, and get a localised day nameā¦
let dayNumber = Calendar.current.component(.weekday, from: Date()) // 1 - 7
let dayName = DateFormatter().weekdaySymbols[dayNumber - 1]
-(void)getdate {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"MMM dd, yyyy HH:mm"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"EEEE"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSString *week = [dateFormatter stringFromDate:now];
NSLog(#"\n"
"theDate: |%#| \n"
"theTime: |%#| \n"
"Now: |%#| \n"
"Week: |%#| \n"
, theDate, theTime,dateString,week);
}
I needed a simple (Gregorian) day of the week index, where 0=Sunday and 6=Saturday to be used in pattern match algorithms. From there it is a simple matter of looking up the day name from an array using the index. Here is what I came up with that doesn't require date formatters, or NSCalendar or date component manipulation:
+(long)dayOfWeek:(NSDate *)anyDate {
//calculate number of days since reference date jan 1, 01
NSTimeInterval utcoffset = [[NSTimeZone localTimeZone] secondsFromGMT];
NSTimeInterval interval = ([anyDate timeIntervalSinceReferenceDate]+utcoffset)/(60.0*60.0*24.0);
//mod 7 the number of days to identify day index
long dayix=((long)interval+8) % 7;
return dayix;
}
Here is the updated code for Swift 3
Code :
let calendar = Calendar(identifier: .gregorian)
let weekdayAsInteger = calendar.component(.weekday, from: Date())
To Print the name of the event as String:
let dateFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
I think this topic is really useful, so I post some code Swift 2.1 compatible.
extension NSDate {
static func getBeautyToday() -> String {
let now = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE',' dd MMMM"
return dateFormatter.stringFromDate(now)
}
}
Anywhere you can call:
let today = NSDate.getBeautyToday()
print(today) ---> "Monday, 14 December"
Swift 3.0
As #delta2flat suggested, I update answer giving user the ability to specify custom format.
extension NSDate {
static func getBeautyToday(format: String = "EEEE',' dd MMMM") -> String {
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: now)
}
}
Vladimir's answer worked well for me, but I thought that I would post the Unicode link for the date format strings.
http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns
This link is for iOS 6. The other versions of iOS have different standards which can be found in the X-Code documentation.
This way it works in Swift:
let calendar = NSCalendar.currentCalendar()
let weekday = calendar.component(.CalendarUnitWeekday, fromDate: NSDate())
Then assign the weekdays to the resulting numbers.
I had quite strange issue with getting a day of week. Only setting firstWeekday wasn't enough. It was also necesarry to set the time zone. My working solution was:
NSCalendar* cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[cal setFirstWeekday:1]; //Sunday
NSDateComponents* comp = [cal components:( NSWeekOfMonthCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSWeekCalendarUnit) fromDate:date];
return [comp weekday] ;
Swift 2: Get day of week in one line. (based on neoscribe answer)
let dayOfWeek = Int((myDate.timeIntervalSinceReferenceDate / (60.0*60.0*24.0)) % 7)
let isMonday = (dayOfWeek == 0)
let isSunday = (dayOfWeek == 6)
self.dateTimeFormatter = [[NSDateFormatter alloc] init];
self.dateTimeFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; // your timezone
self.dateTimeFormatter.locale = [NSLocale localeWithLocaleIdentifier:#"zh_CN"]; // your locale
self.dateTimeFormatter.dateFormat = #"ccc MM-dd mm:ss";
there are three symbols we can use to format day of week:
E
e
c
The following two documents may help you.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
Demo:
you can test your pattern on this website:
http://nsdateformatter.com/
Related
I am working on an app where I need to create a weekly calendar. For this I will need days and dates of current week(Sun Sep30, Mon Oct 1, Tue Oct2 etc.). Can someone please guide me how to achieve this?
Regards
Pankaj
Here is a simple function which extracts date for all the days in this week, staring from Sunday this week to Saturday,
func formattedDaysInThisWeek() -> [String] {
// create calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
// today's date
let today = NSDate()
let todayComponent = calendar.components([.Day, .Month, .Year], fromDate: today)
// range of dates in this week
let thisWeekDateRange = calendar.rangeOfUnit(.Day, inUnit:.WeekOfMonth, forDate:today)
// date interval from today to beginning of week
let dayInterval = thisWeekDateRange.location - todayComponent.day
// date for beginning day of this week, ie. this week's Sunday's date
let beginningOfWeek = calendar.dateByAddingUnit(.Day, value: dayInterval, toDate: today, options: .MatchNextTime)
var formattedDays: [String] = []
for i in 0 ..< thisWeekDateRange.length {
let date = calendar.dateByAddingUnit(.Day, value: i, toDate: beginningOfWeek!, options: .MatchNextTime)!
formattedDays.append(formatDate(date))
}
return formattedDays
}
func formatDate(date: NSDate) -> String {
let format = "EEE MMMdd"
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(date)
}
If you call method formattedDaysInThisWeek(), the output is like this,
["Sun Oct11", "Mon Oct12", "Tue Oct13", "Wed Oct14", "Thu Oct15", "Fri Oct16", "Sat Oct17"]
Do you just need it for this week? If so, here's some code that you should be able to use:
- (NSString *)stringOfDatesOfThisWeek {
NSArray *datesOfThisWeek = [self dateOfTheWeek:[NSDate date]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MMM d"];
NSMutableString *dateStringForThisWeek = [[NSMutableString alloc] initWithString:[formatter stringFromDate:[datesOfThisWeek firstObject]]];
for (int i = 1; i < datesOfThisWeek.count; i++) {
[dateString appendFormat:#", %#", [formatter stringFromDate:[datesOfThisWeek objectAtIndex:i]]];
}
}
- (NSArray *)datesOfTheWeek:(NSDate *)todaysDate {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber = [[calendar components: NSWeekCalendarUnit fromDate:todaysDate] week];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:todaysDate];
[comp setWeek:weekNumber]; //Week number.
NSMutableArray *dates = [NSMutableArray new];
for (int i = 0; i < 7; i++) {
[comp setWeekday:1]; //First day of the week. Change it to 7 to get the last date of the week
NSDate *resultDate = [gregorian dateFromComponents:comp];
[dates addObject:resultDate];
}
return dates;
}
and after typing all of that without Xcode, I realized that this question was asked about Swift. I'm leaving it in case someone wants an Objective-C answer and stumbles across this.
If I understood it correctly, to get expected date format you can use NSDateFormatter with following formatter:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat:#"EEEE, MMM d";
NSLog(#"%#", [dateFormatter stringFromDate:[NSDate date]]);
You can also set locale for date formatter to get weekdays in specified language:
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_GB"]];
For more details please refer to Data Formatting Guide
Updated Objective - c Code of #fennelouski :
- (NSString *)stringOfDatesOfThisWeek {
NSArray *datesOfThisWeek = [self datesOfTheWeek:[NSDate date]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MMM d"];
NSMutableString *dateStringForThisWeek = [[NSMutableString alloc] initWithString:[formatter stringFromDate:[datesOfThisWeek firstObject]]];
for (int i = 1; i < datesOfThisWeek.count; i++) {
[dateStringForThisWeek appendFormat:#", %#", [formatter stringFromDate:[datesOfThisWeek objectAtIndex:i]]];
}
return dateStringForThisWeek;
}
- (NSArray *) datesOfTheWeek:(NSDate *)todaysDate {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber = [[calendar components: NSCalendarUnitWeekOfMonth fromDate:todaysDate] weekOfMonth];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components:NSCalendarUnitYear fromDate:todaysDate];
[comp setWeekOfMonth:weekNumber]; //Week number.
NSMutableArray *dates = [NSMutableArray new];
for (int i = 0; i < 7; i++) {
[comp setWeekday:1]; //First day of the week. Change it to 7 to get the last date of the week
NSDate *resultDate = [gregorian dateFromComponents:comp];
[dates addObject:resultDate];
}
return dates;
}
I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.
I need to get the weekday of the first day of the month. For example, for the current month September 2013 the first day falls on Sunday.
At first, get the first day of current month (for example):
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDate *firstDayOfMonth = [gregorian dateFromComponents:components];
Then use NSDateFormatter to print it as a weekday:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:firstDayOfMonth]);
P.S. also take a look at Date Format Patterns
Here is the solution to getting the weekday name of the first day in the current month
NSDateComponents *weekdayComps = [[NSDateComponents alloc] init];
weekdayComps = [calendar.currentCalendar components:calendar.unitFlags fromDate:calendar.today];
weekdayComps.day = 1;
NSDateFormatter *weekDayFormatter = [[NSDateFormatter alloc]init];
[weekDayFormatter setDateFormat:#"EEEE"];
NSString *firstweekday = [weekDayFormatter stringFromDate:[calendar.currentCalendar dateFromComponents:weekdayComps]];
NSLog(#"FIRST WEEKDAY: %#", firstweekday);
For the weekday index, use this
NSDate *weekDate = [calendar.currentCalendar dateFromComponents:weekdayComps];
NSDateComponents *components = [calendar.currentCalendar components: NSWeekdayCalendarUnit fromDate: weekDate];
NSUInteger weekdayIndex = [components weekday];
NSLog(#"WEEKDAY INDEX %i", weekdayIndex);
You can also increment or decrement the month if needed.
Depending on the output you need you may use NSDateFormatter (as it was already said) or you may use NSDateComponents class. NSDateFormatter will give you a string representation, NSDateComponents will give you integer values. Method weekday may do what you want.
NSDateComponents *components = ...;
NSInteger val = [components weekday];
For Swift 4.2
First:
extension Calendar {
func startOfMonth(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year, .month], from: date))!
}
}
Second:
self.firstWeekDay = calendar.component(.weekday, from: calendar.startOfMonth(Date()))
I am new to objective c. I wish to do the following:
Convert 24 hour format to 12 hour and then add +2 to hour and display it like: 4:00 pm
I get the 12 hour format but after adding +2 to it , the time is displayed always as "am", i.e even if it is 4 pm it is displayed as 4 am. Below is my code:
NSDate *now = [NSDate date];
NSDateFormatter *timeFormatter=[[NSDateFormatter alloc]init];
timeFormatter.dateFormat=#"hh:00 a";
NSString *currentHour=[timeFormatter stringFromDate:now ];
lblcurrentHour.text=[NSString stringWithFormat:#"%#",currentHour];
NSLog(#"%#",currentHour);
int hour=[[timeFormatter stringFromDate:now]intValue];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
dateFormatter1.dateFormat = #"HH:mm";
NSDate *date1 = [dateFormatter1 dateFromString:[NSString stringWithFormat:#"%02d:00",hour+=3]];
dateFormatter1.dateFormat = #"hh:mm a";
lblnextHour.text = [dateFormatter1 stringFromDate:date1]; // prints 4:00 am not pm
How do i solve this? Where am i getting wrong?
If I understand your requirements correctly, you want to take the current time and display the minutes as :00, anchoring to the current hour. Then you want to add two hours and display that time. The following code prints 04:00 AM and 06:00 AM to the console (local time is 0421.)
For calendrical calculations, I would avoid using NSDateFormatter as you are doing when you compute the time two hours from now. There are too many ways that can go astray. For example, what happens when the now time is 2300?
A good reference on calendrical calculations in Cocoa is here
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
// use gregorian calendar for calendrical calculations
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// get current date
NSDate *date = [NSDate date];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
units |= NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *currentComponents = [gregorian components:units fromDate:date];
// change the minutes to 0
currentComponents.minute = 0;
date = [gregorian dateFromComponents:currentComponents];
// format and display the time
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.dateFormat = #"hh:mm a";
NSString *currentTimeString = [timeFormatter stringFromDate:date];
NSLog(#"Current hour = %#",currentTimeString);
// add two hours
NSDateComponents *incrementalComponents = [[NSDateComponents alloc] init];
incrementalComponents.hour = 2;
NSDate *twoHoursLater = [gregorian dateByAddingComponents:incrementalComponents toDate:date options:0];
// format and display new time
NSString *twoHoursLaterStr = [timeFormatter stringFromDate:twoHoursLater];
NSLog(#"Two hours later = %#",twoHoursLaterStr);
}
return 0;
}
Try this:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss a"];
NSLog(#"Today's Date and Time: %#", [formatter stringFromDate:[NSDate date]]);
Output:
Today's Date and Time: 02:43:33 PM
I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.