I would like to return the weekday name of tomorrow (i.e. if today is Sunday, I want Monday). Here's my code that yields today's weekday name.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE"];
weekDay = [formatter stringFromDate:[NSDate date]];
Rather than messing with NSCalendar, what would be a concise way of doing this (following the code I have here)?
Thank you.
user's language aware:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
NSArray *weekdays = [df weekdaySymbols];
NSDateComponents *c = [[NSDateComponents alloc] init];
c.day = 1;
NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:c
toDate:[NSDate date]
options:0];
c = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit
fromDate:tomorrow];
NSString *tomorrowname = weekdays[c.weekday-1];// the value of c.weekday may
// range from 1 (sunday) to 7 (saturday)
NSLog(#"%#", tomorrowname);
if you need to have the name in a certain language, add
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
after the creation of the date formatter.
Why are you afraid of "messing" with NSCalendar? For using the NSDateComponents methods, you will actually have to make use of NSCalendar. This is my solution for your problem.
// Get the current weekday
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
// !! Sunday = 1
NSInteger weekday = [weekdayComponents weekday];
Now, you can use the NSDateFormatter method -(NSArray *)weekdaySymbols which contains weekdays starting with Sunday at index 0. As the integer returned by [weekdayComponents weekday] starts with 0 for Saturday, we do not have to increase the value stored in weekday:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// !! Sunday = 0
NSUInteger symbolIndex = (weekday < 7) ? weekday : 0;
NSString *weekdaySymbol = [[formatter weekdaySymbols] objectAtIndex:(NSUInteger)symbolIndex];
I hope this was helpful although using NSCalendar to some extent.
EDIT: glektrik's solution is pretty straight ahead. But mind the following statement in the NSDate class reference of - dateByAddingTimeInterval:.
Return Value:
A new NSDate object that is set to seconds seconds relative to the receiver. The date returned might have a representation different from the receiver’s.
Thank you for your comment, Abizern. Here's what I did:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE"];
weekDay = [formatter stringFromDate:[NSDate date]];
NSDateComponents *tomorrowComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSDate *compDate = [[NSCalendar currentCalendar] dateFromComponents:tomorrowComponents];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
offsetComponents.day = 1;
NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents toDate:compDate options:0];
nextWeekDay = [formatter stringFromDate:tomorrow];
Two NSString objects (weekDay and nextWeekDay) now store the days of the week names for today and tomorrow (currently Sunday and Monday).
This works well, but I wonder if there's an easier way. Objective-C dates are quite cumbersome :(
Thanks again.
Related
I want to take absolute value from NSDateComponents.
<NSDateComponents: 0x600000477c80>
Calendar Year: -1
I tried the following way.But I did not get the exact value.How can i get the value 1 from the components.
NSDate *startDate = [formatter dateFromString:birthDate];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitYear
fromDate:startDate
toDate:today
options:0];
NSInteger year = [components year];
If you want to get difference of the dates in the years, then you have to use method : calendar: fromDate: toDate:
And if you want to get only year from the date, then you have to use this method : calendar: fromDate:.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy hh:mm:ss"];
NSDate *today = [NSDate date];
NSString *birthDate = #"04/06/1984 01:45:20";
NSDate *startDate = [formatter dateFromString:birthDate];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitYear fromDate:startDate toDate:today options:0]; //Option 1
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitYear fromDate:startDate]; // Option 2
NSInteger year = [components year];
NSLog(#"Years : %ld", year);
If you use method of option 1, then it will print Years : 35.
And if you use method of option 2, then it will give Years : 1984.
Suppose i have two parameters
Australia/Sydney (GMT+10) offset 36000 &
Asia/Kolkata (IST) offset 19800
as timezones, it gives different values for the day component of current day itself. I am not able to figure out what am i doing wrong.. :( A little clue will be appreciated
-(NSInteger)getDayWithTimeZoneName:(NSString *)timeZoneName{
// Instantiate a timezone
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:timeZoneName];
//Instantiate a date formatter
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[NSLocale currentLocale]];
[df setTimeZone:timeZone];
[df setDateFormat:#"yyyy-MM-dd"];
NSString *dateStr = [df stringFromDate:[NSDate date]];
NSDate *date = [df dateFromString:dateStr];
// NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay fromDate:date];
NSDateComponents *components = [[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
NSLog(#"Date component for timeZone %# is %ld", timeZoneName,(long)day);
return day;
}
NSFormatter isn't designed to convert or calculate dates:
NSString *dateStr = [df stringFromDate:[NSDate date]];
dateStr is the date in Sydney (2016-05-16 0:00).
NSDate *date = [df dateFromString:dateStr];
date is GMT, 10 hours behind Sydney (2016-05-15 14:00).
Use NSCalendar to calculate dates:
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = timeZone;
NSDateComponents *components = [calendar components:NSCalendarUnitDay fromDate:[NSDate date]];
NSInteger day = [components day];
What I'm looking for is the day of the month, example 2, 5, 30 or 31. In integer form, and not a string. I'm not looking for a programmed date, but today's date in whatever local they are in.
All the above answers are bad ways to accomplish this. This is the right way:
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:date];
NSInteger day = components.day;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"d"];
NSInteger day = [[dateFormat stringFromDate:[NSDate date]] intValue];
Start with an NSDate then run it through an NSDateFormatter.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
Here is something that may work :
NSDate *theDate;
// Set theDate to the date you want
// For example, theDate = [NSDate date]; to get today's date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"d";
NSString *theDayString = [formatter stringFromDate:theDate];
int theDay = theDayString.intValue;
NSLog (#"%d", theDay);
theDay contains the value you're looking for !
I have a date in string format just like 30-11-2012. I want the date next to it like 01-12-2012 again in string format.
Is there any way of getting it?
You should use NSCalendar for best compatibility
NSDate *today = [NSDate dateWithNaturalLanguageString:#"2011-11-30"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [NSDateComponents new];
dayComponent.day = 1;
today = [calendar dateByAddingComponents:dayComponent toDate:today options:0];
//2011-12-01 12:00:00 +0000
I got the answer by someone I forget the name, I was about to accept his/her answer but when I clicked on accept answer it told me that the post bas been removed.
The answer given by that anonymous person was given below
NSString *dateString = #"22-11-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSDateComponents *components= [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *dateIncremented= [calendar dateByAddingComponents:components toDate:dateFromString options:0];
NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *stringFromDate = [myDateFormatter stringFromDate:dateIncremented];
NSLog(#"%#", stringFromDate);
In the end I really like to thanks that anonymous person, I know this was not as much tricky but this helped me a lot. Thanks again you the Anonymous Helper.
swift 3.0
var components = DateComponents()
components.day = 1
let now = Date()
let futureDate = Calendar.current.date(byAdding: components, to: now, wrappingComponents: false)
//now = 2017-03-22 futureDate = 2017-03-23
I just found a but in one of my apps; the problem is that I am calculating the days in a menu using initWithTimeIntervalSinceNow and adding the caculation (day*X) (X meaning the day in question).
However, the night between 27th and 28th of oct the CEST timezone will become CET thus meaning that for one day the time should be calculated by (day*X)+3600. However, I do not want to use if cases and believe there should be a better way of dealing with this.
How can I calculate future days with keeping summer/winter time in mind?
My code:
int day = (60*60*24);
NSDate *today = [NSDate date];
NSDate *days1 = [[NSDate alloc] initWithTimeIntervalSinceNow:day];
NSDate *days2 = [[NSDate alloc] initWithTimeIntervalSinceNow:(day*2)];
NSDate *days3 = [[NSDate alloc] initWithTimeIntervalSinceNow:(day*3)];
NSDate *days4 = [[NSDate alloc] initWithTimeIntervalSinceNow:(day*4)];
NSDate *days5 = [[NSDate alloc] initWithTimeIntervalSinceNow:(day*5)];
NSDate *days6 = [[NSDate alloc] initWithTimeIntervalSinceNow:(day*6)];
NSDate *days7 = [[NSDate alloc] initWithTimeIntervalSinceNow:(day*7)];
Try this:
- (NSDate *)dateByAddingXDaysFromToday:(int)days
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = days;
return [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:[NSDate date] options:0];
}
Then you can use:
NSDate *days1 = [self dateByAddingXDaysFromToday:1];
//etc...
It's not clear what you are trying to achieve with calculating the date objects. I'm assuming you want to create objects that refer the next seven days, same time as now.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSDate *now = [NSDate date];
NSDate *days1 = [calendar dateByAddingComponents:components toDate:now options:0];
NSDate *days2 = [calendar dateByAddingComponents:components toDate:days1 options:0];
NSDate *days3 = [calendar dateByAddingComponents:components toDate:days2 options:0];
....