I suppose that I ask duplicate question, but I can not find solution for me. I need to get 1st day of the previous month. As I understand I have to get calendar from today, subtract 1 month and set day to be 1st. After that I have to convert to date. Unfortunately I get last day of previous month.
I use following code:
NSDate *maxDate = [[NSDate alloc] init];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:maxDate];
[components setMonth:-1];
components.day = 1;
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#"%#", minDate);
EDIT:
Yes, it is duplicate, but answers in that question does not help me. I still get 30/09/2014 (when today is 17/11/2014) instead of 01/10/2014. I suppose that my problem is time of todays date.
Well, Here a new approach:
NSDate *today = [NSDate date];
NSDateFormatter *formatterYear = [[NSDateFormatter alloc] init];
[formatterYear setDateFormat:#"yyyy"];
NSDateFormatter *formatterMonth = [[NSDateFormatter alloc] init];
[formatterMonth setDateFormat:#"MM"];
[formatterMonth setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *yearString = [formatterYear stringFromDate:today];
NSString *monthString = [formatterMonth stringFromDate:today];
NSInteger month,year;
if ([monthString integerValue] == 1) {
year = [yearString integerValue] -1;
month = 12;
} else
{
year = [yearString integerValue];
month = [monthString integerValue]-1;
}
NSDateFormatter *exitFormatter = [[NSDateFormatter alloc] init];
[exitFormatter setDateFormat:#"yyyy-MM-dd"];
[exitFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *stringDate;
if (month < 10) {
stringDate = [NSString stringWithFormat:#"%ld-0%ld-01",(long)year,(long)month];
} else {
stringDate = [NSString stringWithFormat:#"%ld-%ld-01",(long)year,(long)month];
}
NSDate *firstDatePreviousMonth = [exitFormatter dateFromString:stringDate];
NSLog(#"View the date: %#",[firstDatePreviousMonth description]);
Wrong calculation.
Use this code to set Month component.
[components setMonth:components.month -1];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"MM"];
NSString *stringCurrentDate = [dateFormatter1 stringFromDate:currentDate];
int monthInt= [stringCurrentDate intValue];
[dateFormatter1 setDateFormat:#"yyyy"];
NSString *dateString = [dateFormatter1 stringFromDate:currentDate];
int yearInt = [dateString intValue];
monthInt-= 1;
if (monthInt== 0) {
monthInt= 12;
yearInt -=1;
}
dateString = [NSString stringWithFormat:#"%#-01-%#",[#(monthInt)stringValue],[#(yearInt)stringValue]];
NSLog(#"this is previous month first date : %#",dateString);
run it as it is, obviously first day of month will be 01, so this is static here. your can change accordingly. happy coding
Try this:
NSDate *maxDate = [NSDate date];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitTimeZone | NSCalendarUnitSecond | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:maxDate];
[components setMonth:components.month - 1];
[components setDay:1];
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#">>>>>>>>>>%#", minDate.description);
Related
How do I set maximum date in UIDatepickerView as today 23:59pm.
I tried like this
datePicker.maximumDate = [NSDate date];
But it is not working.
How can I do this?
You can do something like,
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *currentDate = [NSDate date];
NSString *currentDateStr = [[df stringFromDate:currentDate] stringByAppendingString:#" 23:59"];
[df setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *maxDate = [df dateFromString:currentDateStr];
NSLog(#"max date : %#",maxDate);
NSLog(#"max date str : %#",[df stringFromDate:maxDate]);
yourDatePicker.maximumDate = maxDate;
Update :
Another approach using NSDateComponents as suggested by #droppy,
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components: NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];
dateComponents.hour = 23;
dateComponents.minute = 59;
NSLog(#"%ld : %ld : %ld",(long)day,(long)month,(long)year);
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *resultDate = [gregorianCalendar dateFromComponents:dateComponents];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd HH:mm"];
NSLog(#"result date : %#",resultDate);
NSLog(#"result date string : %#",[df stringFromDate:resultDate]);
yourDatePicker.maximumDate = resultDate;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I had Two Dates from date and to date. I stored two dates in NSString like string1 and string 2 respectively. Now My Problem is I want the difference of these two dates. My Date format is 04-Mar-2014 and 14-Mar-2014 and I want the result to be like 10.
You can get difference by using the code given below:-
NSString *start = #"2010-09-01";
NSString *end = #"2010-12-01";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
[f release];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
[gregorianCalendar release];
components now holds the difference.
NSLog(#"%ld", [components day]);
Courtesy:-vikingosegundo
https://stackoverflow.com/a/4576575/1865424
Three methods you need are:
+ (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YOUR_STRING_FORMAT"];
}
[NSTimeZone resetSystemTimeZone];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
return dateFormatter;
}
+ (NSDate *)dateWithString:(NSString *)dateString
{
return [[self dateFormatter] dateFromString:dateString];
}
- (NSInteger)distanceInDaysToDate:(NSDate *)date
{
NSDateComponents *components1 = [CURRENT_CALENDAR components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
components1.hour = 0;
components1.minute = 0;
components1.second = 0;
NSDateComponents *components2 = [CURRENT_CALENDAR components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
components1.hour = 0;
components1.minute = 0;
components1.second = 0;
NSDate *date1 = [CURRENT_CALENDAR dateFromComponents:components1];
NSDate *date2 = [CURRENT_CALENDAR dateFromComponents:components2];
NSDateComponents *components = [CURRENT_CALENDAR components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];
return components.day;
}
Best if you move them into NSDate category.
You Two date is
NSString* str1 = #"04-Mar-2014";
NSString* str2 = #"14-Mar-2014";
Now convert two date in to DD-MM-YYY as below
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
Now string convert into date
NSDate *date1 = [dateFormat dateFromString:str1];
NSDate *date2 = [dateFormat dateFromString:str2];
Calculation of convert between two date
NSTimeInterval distanceBetweenDates = [date2 timeIntervalSinceDate:date1];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSInteger day = hoursBetweenDates/ 24;
Your OUTPUT : 10
I think, according to your question, my assumption is difference between two dates. You can use this.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSDate *date1 = [dateFormat dateFromString:#"04-Mar-2014"];
NSDate *date2 = [dateFormat dateFromString:#"14-Mar-2014"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);
While keeping the NSDate objects is the best solution, you can recreate NSDateobjects from the string using an NSDateFormatter with its format string set accordingly to your date format.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MMM-yy"];
[dateFormatter dateFromString:yourString];
Then you can use for example the timerIntervalSinceDate:method of NSDateand calculate the difference. Alternatively you can extract NSDateComponentsand get the difference that way.
I want show whether particular office is opened or closed depends on the weekday
i am getting office timings from my server
NSString *open = #"10:00 AM";
NSString *close = #"6:00 PM";
NSDateFormatter *df11 = [[NSDateFormatter alloc]init];
[df11 setDateFormat:#"dd-MM-yyyy"];
NSString *date11=[df11 stringFromDate:[NSDate date]];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"dd-MM-yyyy hh:mm a"];
NSDate *date1 = [NSDate date];
NSString *dte1 = [df stringFromDate:date1];
date1 = [df dateFromString:dte1];
NSString *dte2 = [NSString stringWithFormat:#"%# %#",date11, open];
NSDate *date2 = [df dateFromString:dte2];
NSString *dte3 = [NSString stringWithFormat:#"%# %#",date11,close];
NSDate *date3 = [df dateFromString:dte3];
if([date1 compare:date2]==NSOrderedDescending && [date1 compare:date3]==NSOrderedAscending)
open=YES;
else
open=NO;
In this case i didn't get any problem, but for some other office i got like this
NSString *open = #"11:30 AM";
NSString *close = #"12:30 AM";/*means here day is changing but still i am using current date
for this case the above code is not working, bcoz of day changes, i am not getting any idea how to follow, i was struggling from last day for solution
please help me
thank you
get days between two dates
NSDate *date1 = [NSDate dateWithString:#"2013-08-08"];
NSDate *date2 = [NSDate dateWithString:#"2013-09-09"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);
You can also get different between two dates GO
Extract the week day and hour from the date and do an explicit test on them:
const NSInteger openHour = 10;
const NSInteger closeHour = 18;
NSDate *dateToTest = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit|NSHourCalendarUnit
fromDate:dateToTest];
BOOL open =
[components weekDay] >= [calendar firstWeekDay] &&
[components weekDay] < [calendar firstWeekDay] + 5 &&
[components hour] >= openHour &&
[components hour] < closeHour;
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.
This question already has answers here:
Calculate number of days remaining [duplicate]
(5 answers)
Closed 8 years ago.
i want to remaning days from array of birthdates im using following code for it
for(int i =0;i<_convertedBdates.count;i++){
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/YYYY"];
NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];
NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
NSDate *secondDate = [tempFormatter dateFromString:curYear];
NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int day = dateDiff/(3600*24);
NSLog(#" _newlymadeArray %#",[_convertedBdates objectAtIndex:i]);
NSLog(#" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:#"%d",day] ];
}
NSLog(#" days %#",_daysremaining);
what wrong i am doing why i am not getting correct days
for(int i =0;i<_convertedBdates.count;i++){
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/YYYY"];
NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];
NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
NSDate *secondDate = [tempFormatter dateFromString:curYear];
NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int day = dateDiff/(3600*24);
day = day -1;
NSLog(#" _newlymadeArray %#",[_convertedBdates objectAtIndex:i]);
NSLog(#" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:#"%d",day] ];
}
NSLog(#" days %#",_daysremaining);
try like this it will help you,
NSString *start = #"03/12/2013";
NSString *end = #"09/12/2013";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"dd/mm/yyyy"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"%d",[components day]);
Keep your code simple :
You can use a method and call it within your calculation block:
- (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar=[NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSDayCalendarUnit
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}