selecting only working days from NSDate in objective c - ios

My concern is..if am having text field with start date.when i am selecting date from calendar with day of Friday..then i want to skip weekend days saturday and sunday in enddate text field...i tried like this
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Date and Time: %#",strCurrentDate);
int hoursToAdd = roundedUp;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(#"New Date and Time: %#",strNewDate);
while ([strNewDate compare:strCurrentDate] == NSOrderedAscending)
{
NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:strNewDate];
if (dateComponents.weekday == friday)
{
count = count+2;
NSLog(#"count = %d", count);
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:2];
NSString *endDate = [strNewDate dateByAddingTimeInterval:2*60*60*24];
// [oneDay setDay:2];
}
}
But I am not getting only week days… so can any one do the needful… thank u in advance :)

To get the next working day from now use the method isDateInWeekend of NSCalendar
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Strip the time portion of the date
NSDate *date = [calendar startOfDayForDate:[NSDate date]];
do {
// add 1 day until the result is not in a weekend
date = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:date options:NSCalendarMatchNextTime];
} while (![calendar isDateInWeekend:date]);
NSLog(#"Next Workday: %#", date);

Related

Unable to store proper date in NSDate

I am trying to store dates in NSDate but not getting proper output.
Writing the code snippet below.
NSDate *firstDate = [NSDate dateWithYear:2015 month:12 day:1 ];
Expecting the output to be 2015-12-1 18:30:00 +0000.
But getting 2015-11-30 18:30:00 +0000
Ignore the time stamp.
dateWithYear:month:day is a category method which is there in the 3rd party calendar which I am using.the code of the method is as follows:
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [NSDate componentsWithYear:year month:month day:day];
return [calendar dateFromComponents:components];
}
return [calendar dateFromComponents:components];
is
+ (NSDateComponents *)componentsWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
return components;
}
Thanks in Advance.
There are many ways to set a date from data,
NSDateFormatter :
NSString *dateString = #"2015-12-01";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date1 = [dateFormatter dateFromString:dateString];
NSDateComponents : (you can add setSecond, setMinute, setHour for a specific time)
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setYear:2015];
[dateComps setMonth:12];
[dateComps setDay:1];
NSDate *date2 = [[NSCalendar currentCalendar] dateFromComponents:dateComps];

Thread1: EXC_BAD_ACCESS(code=1,address=0x5146a345)

i am trying to implement calendar. i have one label for year and two buttons for incrementing and decrementing year from calendar. i am getting this exception (Thread1: EXC_BAD_ACCESS(code=1,address=0x5146a345)) while clicking button(increment or decrement)my requirement is if i click right button my year should increase as well as if i click left button my year should decrease. my exception line is date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0]; could you please help to resolve this issue. this is my code
- (void)viewDidLoad
{
[super viewDidLoad];
date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
- (IBAction)right:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
- (IBAction)left:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
You need a date component to change the date like this,
-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:numOfYears];
return [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents
toDate:date options:0]; }
Pass the offset as 1 for right and -1 for left

Weird date result adding 1 month to a given date

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.

Add 3 Hours to an NSDate's Hour

I want to add 3 hours to my current date. I am using the following code to add hours but it adds 6 hours to the current date.
NSDate *n = [NSDate date];
int daysToAdd = 3; // or 60 :-)
// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init] autorelease];
[components1 setHour:daysToAdd];
// create a calendar
NSCalendar *gregorian12 = [NSCalendar currentCalendar];
NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n options:0];
NSLog(#"Clean: %#", newDate2);
Result is :-
2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
Try this
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Date and Time: %#",strCurrentDate);
int hoursToAdd = 3;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(#"New Date and Time: %#",strNewDate);
Output
Current Date and Time: Sep 10, 2013, 1:15:41 PM
New Date and Time: Sep 10, 2013, 4:15:41 PM
NSDate *CurrentTimedate = [NSDate date];
NSLog(#"%#",CurrentTimedate);
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(#"%#",newDate);
NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];

find total number of days between two dates in iphone

I would like to find total number of days between two dates.
e.g. today is 01-01-2011(DD-MM-YYYY) and second date is (25-03-2011), how would I find the total number of days?
NSDate *currentdate=[NSDate date];
NSLog(#"curretdate is ==%#",currentdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-mm-YYYY hh:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:#"20-04-2011 09:00:00"];
NSLog(#"toDate ==%#",toDate);
In your date Format tor u set wrong it`s be dd-MM-yyyy HH:mm:ss . may be that was the problem.. u get wrong date and not get answer i send litte bit code for get day diffrence.
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *startdate = [tempFormatter dateFromString:#"15-01-2011 09:00:00"];
NSLog(#"startdate ==%#",startdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:#"20-01-2011 09:00:00"];
NSLog(#"toDate ==%#",toDate);
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
NSLog(#"Total Days Between::%d",days);
Edit 1:
we can find date difference using following function :
-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
// Manage Date Formation same for both dates
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:date1];
NSDate *endDate = [formatter dateFromString:date2];
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
return dayDiff;
}
from Abizern`s ans. find more infromation for NSDateComponent here.
NSCalendar *Calander = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[dateFormat setDateFormat:#"dd"];
[comps setDay:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"MM"];
[comps setMonth:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"yyyy"];
[comps setYear:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"HH"];
[comps setHour:05];
[dateFormat setDateFormat:#"mm"];
[comps setMinute:30];
NSDate *currentDate=[Calander dateFromComponents:comps];
NSLog(#"Current Date is :- '%#'",currentDate);
[dateFormat setDateFormat:#"dd"];
[comps setDay:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"MM"];
[comps setMonth:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"yyyy"];
[comps setYear:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"HH"];
[comps setHour:05];
[dateFormat setDateFormat:#"mm"];
[comps setMinute:30];
NSDate *reminderDate=[Calander dateFromComponents:comps];
//NSLog(#"Current Date is :- '%#'",reminderDate);
//NSLog(#"Current Date is :- '%#'",currentDate);
NSTimeInterval ti = [reminderDate timeIntervalSinceDate:currentDate];
//NSLog(#"Time Interval is :- '%f'",ti);
int days = ti/86400;
[dateFormat release];
[Calander release];
[comps release];
Hope It will work for you........
A simpler way of doing it is:
// This just sets up the two dates you want to compare
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:#"01-01-2011"];
NSDate *endDate = [formatter dateFromString:#"25-03-2011"];
// This performs the difference calculation
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
// This just logs your output
NSLog(#"Start Date, %#", startDate);
NSLog(#"End Date, %#", endDate);
NSLog(#"%ld", [difference day]);
And the results are:
Start Date, 2011-01-01 00:00:00 +0000
End Date, 2011-03-25 00:00:00 +0000
83
Trying to use and manipulate seconds for calculating time differences is a bad idea. There are a whole load of classes and methods provided by Cocoa for Calendrical calculations and you should use them as much as possible.
Try this
- (int) daysToDate:(NSDate*) endDate
{
//dates needed to be reset to represent only yyyy-mm-dd to get correct number of days between two days.
NSDateFormatter *temp = [[NSDateFormatter alloc] init];
[temp setDateFormat:#"yyyy-MM-dd"];
NSDate *stDt = [temp dateFromString:[temp stringFromDate:self]];
NSDate *endDt = [temp dateFromString:[temp stringFromDate:endDate]];
[temp release];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt toDate:endDt options:0];
int days = [comps day];
[gregorian release];
return days;
}
//try it
if((![txtFromDate.text isEqualToString:#""]) && (![txtToDate.text isEqualToString:#""]))
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSDate *startDate = [formatter dateFromString:txtFromDate.text];
NSDate *endDate = [formatter dateFromString:txtToDate.text];
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
lblNoOfDays.text =[NSString stringWithFormat:#"%d",dayDiff];
}
to find the number of dates between start date to end date.
NSCalendar *cale=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags=NSMonthCalendarUnit| NSDayCalendarUnit;
NSDateComponents *comp1=[cale components:unitFlags fromDate:startDate toDate:endDate options:0];
NSInteger days=[comp1 day];
NSLog(#"Days %ld",(long)days);
NSDate *dateA;
NSDate *dateB;
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:dateA
toDate:dateB
options:0];
NSLog(#"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
//write this code in .h file
{
NSDate *startDate,*EndDate;
NSDateFormatter *Date_Formatter;
}
//write this code in .h file`enter code here`
- (void)viewDidLoad
{
[super viewDidLoad];
Date_Formatter =[[NSDateFormatter alloc]init];
[Date_Formatter setDateFormat:#"dd-MM-yyyy"];
UIToolbar *numbertoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numbertoolbar.barStyle = UIBarStyleBlackTranslucent;
numbertoolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:#"Next"
style:UIBarButtonItemStyleDone target:self action:#selector(doneWithNumberPad)],nil];
[numbertoolbar sizeToFit];
Txt_Start_Date.inputAccessoryView = numbertoolbar;
[Txt_Start_Date setInputView:Picker_Date];
Txt_End_Date.inputAccessoryView = numbertoolbar;
[Txt_End_Date setInputView:Picker_Date];
[Picker_Date addTarget:self action:#selector(updateTextfield:) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)doneWithNumberPad
{
if ([Txt_Start_Date isFirstResponder])
{
[Txt_Start_Date resignFirstResponder];
[Txt_End_Date becomeFirstResponder];
}
else if([Txt_End_Date isFirstResponder])
{
[Txt_End_Date resignFirstResponder];
startDate =[Date_Formatter dateFromString:Txt_Start_Date.text];
EndDate =[Date_Formatter dateFromString:Txt_End_Date.text];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:startDate toDate:EndDate options:0];
Lab_Total_Days.text =[NSString stringWithFormat:#"%ld",components.day];
}
}
Please try this. Hope it helps you...
NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:#"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:#"MM/dd/YYYY HH:mm "] // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(#"%#f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];

Resources