Following is my code:
NSDateComponents *componenetsForEnd = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:endDate];
NSInteger endDay = [componenetsForEnd day];
NSInteger endMonth = [componenetsFoeEnd month];
NSInteger endDayValue = componenetsForEnd.weekday;
Now: when endDate = 2015-08-31 23:59:59 +0000, I am getting month as 9! This is causing wrong endDayValue. What is going wrong here?
EDIT:
Here is how I calculate endDate :
NSDate *endDate = [self endOfMonthForDate:todayDate];
this method takes today's date with [NSDate date] and this is how it goes:
- (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd andDate: (NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents * months = [[NSDateComponents alloc] init];
[months setMonth: monthsToAdd];
return [calendar dateByAddingComponents: months toDate: date options: 0];
}
- (NSDate *) endOfMonthForDate: (NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDate * plusOneMonthDate = [self dateByAddingMonths: 1 andDate:date];
NSDateComponents * plusOneMonthDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: plusOneMonthDate];
NSDate * endOfMonth1 = [[calendar dateFromComponents: plusOneMonthDateComponents] dateByAddingTimeInterval: -1]; // One second before the start of next month
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:endOfMonth1];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:endOfMonth1];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* endOfMonth = [[NSDate alloc] initWithTimeInterval:interval sinceDate:endOfMonth1];
return endOfMonth;
}
Also tried performing these actions to make NSDateComponents and NSDate with dateFormatter in systemTimeZone:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSString *endDateString = [dateFormatter stringFromDate:endDate];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
[dateFormatter2 setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter2.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSDate *endDateProper = [dateFormatter2 dateFromString:endDateString];
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componenetsForEnd = [greCalendar components:NSWeekdayCalendarUnit | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:endDateProper];
[componenetsForEnd setTimeZone:[NSTimeZone systemTimeZone]];
Instead of using current calendar
[NSCalendar currentCalendar]
you can use:
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
The problem was with the fact that I think is this way: When calculating a day, month or Hour, minute and second , you need to specify that timezone for dateComponents is UTC i.e. GMT. However, my endDateProper which is in system timezone.
So, doing this did the trick for me:
NSDateComponents *componenetsForEnd = [greCalendar componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"] fromDate:endDateProper];
Related
I am having a NSDate object in format as 2018-01-19 18:30:00 +0000. Now i want to change only the time components. After changing the time components the NSDate Object would be as 2018-01-19 10:00:00. I did tried various solution but nothing worked. If any one have any solution regarding this issue help out. Thank you in advance
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay fromDate:date];
[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *newDate = [calendar dateFromComponents:components];
another solution i tried is
NSDate *oldDate = date;
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
comps.hour = 10;
comps.minute = 00;
comps.second = 00;
NSDate *newDate = [calendar dateFromComponents:comps];
Every time i get output is next date of input date
You can change the time components when you create a new NSDate object with:
NSDate *date = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];
Answer from: https://stackoverflow.com/a/5611700/4535184
Here is your code just add dateformater to formate the date
NSDate *oldDate = [[NSDate alloc]init];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
comps.hour = 10;
comps.minute = 00;
comps.second = 00;
NSDate *newDate = [calendar dateFromComponents:comps];
NSDateFormatter *formater = [[NSDateFormatter alloc]init];
formater.dateFormat = #"YYYY-MM-dd hh:mm:ss";
NSLog(#"New Date : %#",[formater stringFromDate:newDate]);
Try this
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss zzzz"];
NSDate *date = [formatter dateFromString:#"2018-01-19 18:30:00 +0000"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSCalendarUnitDay| NSCalendarUnitHour| NSCalendarUnitMinute|NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:date];
[components setHour:10];
[components setMinute:0];
[components setSecond:0];
NSDate *newDate = [calendar dateFromComponents:components];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"%#",[formatter stringFromDate:newDate]);
I am using
- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts
to calculate a new date, like below:
NSDateComponents *quaterComps = [NSDateComponents new];
quaterComps.quarter = 1;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *nextDate = [gregorian dateByAddingComponents:quaterComps toDate:firstDate options:0];
When firstDate is 2013-12-31 16:00:00 +0000,
Above API keeps returning the same result, not the next quarter date
** current date and next date **
NSDate *currentDate = [NSDate date];
NSDate *futureTime = [currentDate dateByAddingTimeInterval:60*60*72];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[calendar setTimeZone:timeZone];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:futureTime];
if ([components hour] >= 19) { // make it the next day
[components setDay:[components day] + 1 ];
}
[components setHour:8];
[components setMinute:00];
NSDate *alertTime = [calendar dateFromComponents:components];
NSDate *date = [NSDate date];
NSDateComponents *comp = [NSDateComponents new];
comp.weekOfYear = 3;
NSDate *date1 = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];
NSLog(#"date: %#", date);
NSLog(#"date1: %#", date1)
I have a requirement in which i have to calculate working days i.e from Monday to Friday. if i pass todays date that particular week start date (Monday's Date) and end date(Friday's Date) will be displayed. And i calculated using the below Code.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];// you can use your format.
todayDate= [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:todayDate];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:todayDate] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"yyyy-MM-dd"];
NSString * dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
NSDate * weekstartPrev = [dateFormat_first dateFromString:dateString2Prev];
// NSLog(#"The start of the week %#",weekstartPrev);
startDate= [weekstartPrev dateByAddingTimeInterval:60*60*24*1];
//NSLog(#"The date plus one is %#", startDate);
//Week End Date
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:todayDate];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:todayDate] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:#"yyyy-MM-dd"];
NSString *dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
NSDate *weekEndPrev = [dateFormat_End dateFromString:dateEndPrev];
endDate= [weekEndPrev dateByAddingTimeInterval: -86400.0];
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateFormat:#"dd-MMM-yyyy"];
[dateF setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateF setLocale:[NSLocale localeWithLocaleIdentifier:#"en_GB"]];
endDateString = [dateF stringFromDate:endDate]; //pass this date to time table view controller
NSLog(#"Start date %# and End date %# ",startDate, endDate);
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateFormat:#"dd-MMM-yyyy"];
[dateF setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateF setLocale:[NSLocale localeWithLocaleIdentifier:#"en_GB"]];
startDateString = [dateF stringFromDate:startDate];
NSLog(#"the date start %# ", startDateString);
Now My question is how can I calculate next week for example todays date is Tue 26 Aug 2014. I calculated the current week i.e from Mon 25 Aug 2014 TO Fri 29 Aug 2014 using the above code. how can I calculate next week i.e from 1st September 2014 (monday) To 5th September 2014 (Friday).
i have worked on the similar issues some weeks ago.
I created a category on NSDate. You can use the methods.
- (NSDate *)firstDayOfWeek
{
return [NSDate firstDayOfWeekFor:self];
}
+(NSDate *)firstDayOfWeekFor:(NSDate*)p_Date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:p_Date];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
if ([weekdayComponents weekday] == 1)
{
// dimanche, on soustrait 6 jours
[componentsToSubtract setDay:-6];
}
else
{
// autres jours, on soustrait le jour courant et on rajoute 2 (=lundi)
[componentsToSubtract setDay:(-[weekdayComponents weekday] + 2)];
}
return [calendar dateByAddingComponents:componentsToSubtract toDate:[p_Date withoutTime] options:0];
}
- (NSDate *) dateByAddingDays:(NSInteger)p_Days
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:p_Days];
return [calendar dateByAddingComponents:components toDate:self options:0];
}
I am using following piece of code to get next week date from a given date at 12:00am:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit |NSHourCalendarUnit fromDate:now];
[components setHour:0];
NSDate *todayDate = [calendar dateFromComponents:components];
int daysToAdd = 7;
NSDate *tomorrowDate = [todayDate dateByAddingTimeInterval:60*60*24*daysToAdd];
NSString *stringDate = [NSString stringWithFormat:#"%#",tomorrowDate];
todoItemDueDateText.text = stringDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEEE, dd MMMM YYYY"];
NSString *fechasimulada = [dateFormatter stringFromDate:tomorrowDate];
dateFieldSimulatedText.text = fechasimulada;
If I log the result date, it is working fine.
Now, a similar piece of code to get next month date from a given date at 12:00am:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:0];
NSDate *todayDate = [calendar dateFromComponents:components];
//NSDate *today = [NSDate date];
NSDateComponents* dateComponents = [[NSDateComponents alloc]init];
[dateComponents setMonth:1];
//NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* tomorrowDate = [calendar dateByAddingComponents:dateComponents toDate:todayDate options:0];
NSString *stringDate = [NSString stringWithFormat:#"%#",tomorrowDate];
todoItemDueDateText.text = stringDate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEEE, dd MMMM YYYY"];
NSString *fechasimulada = [dateFormatter stringFromDate:tomorrowDate];
I don't know why, but the second piece of code gives the expected date but -1 hour.
UPDATE:
I will show you the dates:
Source date (today at 12:00am)+7 h
Next week date from previous given date:
Next month date from previous given date:
NSDate takes Daylight Savings into account. If you cross a DST day, you'll experience this issue.
How can I have the title of UITableview with date?
I know I can edit the title using:
self.title=#"meals for ..";
I want to add the date for one week. How can I do that?
You can get a date like this:
NSDate *theDateToday = [NSDate date];
And format it like this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE MMM dd"];
NSString *theDateAsAString = [dateFormatter stringFromDate:theDateToday];
Combine that with what you have like this:
self.title = [NSString stringWithFormat:#"meals for %#", theDateAsAString];
As for finding the days of the week, you could try adapting this answer.
- (NSString *)getWeekStartDateAsString:(NSDate *)date {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
return weekstartPrev;
}
- (NSString *)getWeekEndDateAsString:(NSDate *)date {
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:#"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
return weekEndPrev;
}
You end result might look like this:
self.title = [NSString stringWithFormat:#"meals for %#-%#", [self getWeekStartDateAsString:theDateToday], [self getWeekEndDateAsString:theDateToday]];
A rarely known NSCalendar method will be the best option IMO
rangeOfUnit:startDate:interval:forDate:. It gives you the start and the duration (interval) for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.
With the also rarely seen localizedStringFromDate:dateStyle:timeStyle: Available in OS X v10.6, iOS 4.0 it is easy to create a localized representation of the dates.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfWeek is 2013-06-02 22:00:00 +0000 now (note: it is GMT with timezone support for my timezone Europe/Berlin/DST)
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
// 2013-06-09 21:59:59 +0000
NSString *text = [NSDateFormatter localizedStringFromDate:startOfTheWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle];
text = [text stringByAppendingString:#" to "];
text = [text stringByAppendingFormat:#"%#", [NSDateFormatter localizedStringFromDate:endOfWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle]];
self.title=text;
results in 03.06.13 to 09.06.13 for my german locale, where Monday is start of the week.