How to check the date cross the sunday and rest data - ios

How to check the date cross the Sunday and reset the data?
I need to do reset on every Sunday, if I missed that on Sunday then the reset need to happen if user open the app the following increment date(i.e mon,tue, till saturday).
For Every Sunday or crossed the Sunday one time the reset need to happened, if user forgot to open the application on Rest date.
Following the my code which i try to implemented.
Which was not working as per my requirement, Your feedback is highly appreciated.
-(void) weekDaySundayToRefresh
{
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday fromDate:now];
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
nextSunday= [now dateByAddingTimeInterval:60*60*24*daysToSunday];
NSLog(#"nextMonday : %#", nextSunday);
}
-(void) compareDate
{
NSDate *today = [NSDate date]; // it will give you current date
// NSDate *newDate = [MH_USERDEFAULTS objectForKey:#"USER_BACKGROUND_DATE"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:refreshGoalsDate]; // comparing two dates
if(result==NSOrderedAscending)
{
NSLog(#"today is less");
}
else if(result==NSOrderedDescending)
{
NSLog(#"newDate is less");
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:refreshGoalsDate];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:today];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
noOfDaysCount = [difference day];
NSLog(#"date difference:%ld",(long)[difference day]);
}
else
NSLog(#"Both dates are same");
}
-(void) checkRefreshGoals:(int)sectionIndex rowIndex:(int)rowIndex
{
NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString * currentDateString = [formatter stringFromDate:[NSDate date]];
NSString * initialNotificationDate = [formatter stringFromDate:refreshDate];
NSDate *currentDate = [formatter dateFromString:currentDateString];
NSDate *refreshDate = [formatter dateFromString:initialNotificationDate];
if ([refreshDate compare:currentDate] == NSOrderedDescending)
{
NSLog(#"date1 is later than date2");
isGoalsRefreshed = NO;
}
else if ([refreshDate compare:currentDate] == NSOrderedAscending)
{
NSLog(#"date1 is earlier than date2");
if (sameDay == YES)
{
isGoalsRefreshed = YES;
[self refreshDataOnSunday:sectionIndex rowIndex:rowIndex];
}
else if (noOfDaysCount > 7)
{
isGoalsRefreshed = YES;
[self refreshDataOnSunday:sectionIndex rowIndex:rowIndex];
}
else
{
isGoalsRefreshed = NO;
}
}
else
{
NSLog(#"dates are the same");
isRefreshed = NO;
}
}
-(void) refreshDataOnSunday:(int)sectionIndex rowIndex:(int)rowIndex
{
if (noOfDaysCount > 7)
{
if (isGoalsRefreshed == YES)
{
// Do rest your data
}
}
else if (sameDay == YES)
{
if (isGoalsRefreshed == YES)
{
// Do reset your data
}
}
else
{
isGoalsRefreshed = NO;
}
}

First you need to save todays date and DayNumber when user opens your app at first time and then you need to compare next app open date so you can estimate either Sunday is gone or not.
/*first check in userDefault for stored Date and Day
Store values in local and check with current date */
NSMutableDictionary *dictStoredData = [USERDEFAULT valueForKey:#"dateTimeDate"];
if (!dictStoredData) {
// user comes first time so store it here
dictStoredData =[[NSMutableDictionary alloc] init];
NSDate *today =[NSDate date];
NSCalendar *gregorian =[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps =[gregorian components:NSCalendarUnitWeekday fromDate:[NSDate date]];
NSInteger weekday = [comps weekday];
int nextSundayVal = 7 - (int)weekday;
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSString *startDate = [format stringFromDate: today];
[dictStoredData setObject:startDate forKey:#"startDate"];
[dictStoredData setObject:[NSString stringWithFormat:#"%d",nextSundayVal] forKey:#"nextSundayVal"];
[USERDEFAULT setObject:dictStoredData forKey:#"dateTimeDate"];
}
else{
NSString *strEndDate = #"2017-01-08";
NSString *strStartDate = [dictStoredData valueForKey:#"startDate"];
int nextSundayVal = (int)[dictStoredData valueForKey:#"nextSundayVal"];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [format dateFromString:strStartDate];
NSDate *endDate = [format dateFromString:strEndDate];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];
int newDayCount = (int)[components day];
if (newDayCount > nextSundayVal) {
NSLog(#"sunday is gone so reload data!!");
//save this date as a new date and check with this when user come again
}
else {
NSLog(#"sunday is not come yet!!");
}
}
here strEndDate is next date when user opens your application so you can get it from [NSDate date] with same dateformater.
I have run this code in my machine and its printing sunday is gone so reload data so hope this will help you.

As like you we had flow, every friday and more than seven days, its need to update the server.
We did it with following code:
You need to update last updated date.
Check this out:
if ([isFirday isEqualToString:#"Friday"]) {//This is my value from server side (they will give as friay), i think you dont need this condition.
BOOL isSameDay;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM dd yyyy,HH:mm"];
NSDate *date = [dateFormatter dateFromString:mennuRefreshTime];//Is an last updated date.
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *temp = [dateFormatter stringFromDate:date];
NSDate *lastDate = [dateFormatter dateFromString:temp];
NSString *currentDaystr = [dateFormatter stringFromDate:[NSDate date]];
// Write the date back out using the same format
NSDate *currentDate = [dateFormatter dateFromString:currentDaystr];
if ([lastDate compare:currentDate] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
isSameDay = NO;
} else if ([lastDate compare:currentDate] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
[dateFormatter setDateFormat:#"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:currentDate];
NSString *lastupdateName = [dateFormatter stringFromDate:lastDate];
if ([dayName isEqualToString:lastupdateName]) {
isSameDay = YES;
}else{
isSameDay = NO;
}
} else {
NSLog(#"dates are the same");
isSameDay = YES;
}
if (isSameDay == YES) {
return;
}
NSCalendar *calender =[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calender components:NSCalendarUnitDay fromDate:lastDate toDate:currentDate options:0];
int day = (int)[components day];
if (day >= 7) {
[self getTopList];
}else{
[dateFormatter setDateFormat:#"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:currentDate];
if ([dayName isEqualToString:isFirday]) {
[self getTopList];
}else{
return;
}
}
}

Related

How to get date and time in format like - [Today 10:01:20], [08-jan-17 11:20:51] etc?

I am working on chat apps and I want to send date/time in particular format like Today, yesterday with date. How can I display according to this format?
- (NSString *)relativeDateStringForDate:(NSDate *)date
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear |
NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
fromDate:date
toDate:[NSDate date]
options:0];
if (components.year > 0) {
return [NSString stringWithFormat:#"%ld years ago", (long)components.year];
} else if (components.month > 0) {
return [NSString stringWithFormat:#"%ld months ago", (long)components.month];
} else if (components.weekOfYear > 0) {
return [NSString stringWithFormat:#"%ld weeks ago", (long)components.weekOfYear];
} else if (components.day > 0) {
if (components.day > 1) {
return [NSString stringWithFormat:#"%ld days ago", (long)components.day];
} else {
return #"Yesterday";
}
} else
{
return #"Today";
}
}
I am using above function to get date but I want date time in combined string. So how to pass date/time combine to the above method? Is it possible to send a date time string to this method?
For getting the date in format [08-jan-17 11:20:51], you can use the below code
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Convert to new Date Format
[dateFormatter setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSDate *date = [NSDate date];
NSString *newDate = [dateFormatter stringFromDate:date]
NSLog(#"[%#]",newDate); // this will give you the date in format [08-jan-17 11:20:51]
For getting the time in format [10:01:20], you can use the below code
// Convert to new Time Format
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSDate *date = [NSDate date];
NSString *newTime = [dateFormatter stringFromDate:date];
NSLog(#"%#",newTime); // this will give you the time in format 10:01:20
So you can use your code like this -
- (NSString *)relativeDateStringForDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Convert to new Date Format
[dateFormatter setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSString *newDate = [dateFormatter stringFromDate:date];
NSLog(#"[%#]",newDate);
// Convert to new Time Format
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSString *newTime = [dateFormatter stringFromDate:date];
NSLog(#"%#",newTime);
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear |
NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
fromDate:date
toDate:[NSDate date]
options:0];
if (components.year > 0) {
return [NSString stringWithFormat:#"[%ld years ago], [%#]", (long)components.year, newDate];
} else if (components.month > 0) {
return [NSString stringWithFormat:#"[%ld months ago], [%#]", (long)components.month, newDate];
} else if (components.weekOfYear > 0) {
return [NSString stringWithFormat:#"[%ld weeks ago], [%#]", (long)components.weekOfYear, newDate];
} else if (components.day > 0) {
if (components.day > 1) {
return [NSString stringWithFormat:#"[%ld days ago], [%#]", (long)components.day, newDate];
} else {
return [NSString stringWithFormat:#"[Yesterday %#]",newTime];
}
} else
{
return [NSString stringWithFormat:#"[Today %#]", newTime];
}
}
A couple of observations:
You want NSCalendarUnitWeekOfMonth, not NSCalendarUnitWeekOfYear.
In order to distinguish between "today" and "yesterday", you can't just get the date components between two NSDate objects. You should get the date components (but not time components) of the two dates first, and then get the difference between those two sets of date components.
As it is, if it's 9am and you're looking at a message from 11pm last night, it will calculate that day < 1, and thus it will say "Today 11pm" (which is wrong) rather than "Yesterday 11pm".
If you're going to include that "x months ago" string, I'd suggest getting out of the business of building it yourself. Apple has a class that does that for you (NSDateComponentsFormatter) and it's localized.
So, pulling that all together, you get something like:
- (NSString *)relativeDateStringForDate:(NSDate *)date {
// get the number of days differences
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitMonth | NSCalendarUnitYear;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:units fromDate:date];
NSDateComponents *nowComponents2 = [calendar components:units fromDate:[NSDate date]];
NSDateComponents *components = [calendar components:units fromDateComponents:dateComponents toDateComponents:nowComponents2 options:0];
if (components.year > 0 || components.month > 0 || components.weekOfMonth > 0 || components.day > 1) {
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = units;
formatter.maximumUnitCount = 2; // set this to whatever you want, but 1 or 2 is often best
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
return [NSString stringWithFormat:#"%# %#", [formatter stringFromDateComponents:components], NSLocalizedString(#"ago", #"x days _ago_")];
} else {
// build time string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *timeString = [formatter stringFromDate:date];
if (components.day == 1) {
return [NSString stringWithFormat:#"%# %#", NSLocalizedString(#"Yesterday", #"day before today"), timeString];
} else {
return [NSString stringWithFormat:#"%# %#", NSLocalizedString(#"Today", #"well, er, today"), timeString];
}
}
}
Now, notice that I excluded the time if the date was before yesterday. The time doesn't make sense if the date string is measured in any units greater than days (e.g. the time is meaningless in this string: "3 months ago, 11:20am"). If you want to include the time, you have to include the date (which then renders these relative "ago" strings useless). So you might just get rid of this "ago" portion:
- (NSString *)relativeDateStringForDate:(NSDate *)date {
// get the number of days differences
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitMonth | NSCalendarUnitYear;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:units fromDate:date];
NSDateComponents *nowComponents2 = [calendar components:units fromDate:[NSDate date]];
NSDateComponents *components = [calendar components: NSCalendarUnitDay fromDateComponents:dateComponents toDateComponents:nowComponents2 options:0];
if (components.day > 1) {
// build date/time string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterShortStyle;
formatter.dateStyle = NSDateFormatterShortStyle;
return [formatter stringFromDate:date];
} else {
// build time string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *timeString = [formatter stringFromDate:date];
if (components.day == 1) {
return [NSString stringWithFormat:#"%#, %#", NSLocalizedString(#"Yesterday", #"day before today"), timeString];
} else {
return [NSString stringWithFormat:#"%#, %#", NSLocalizedString(#"Today", #"well, er, today"), timeString];
}
}
}
That solves the weird "3 months ago, 11:20am" problem, but then again, it's no longer a relative date/time string.
Another option is to abandon absolute time altogether, and just show a relative string:
- (NSString *)relativeDateStringForDate:(NSDate *)date {
NSCalendarUnit units = NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = units;
formatter.maximumUnitCount = 2;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
return [NSString stringWithFormat:#"%# %#", [formatter stringFromDate:date toDate:[NSDate date]], NSLocalizedString(#"ago", #"x days _ago_")];
}
The details of the above samples is less important than the basic concepts, namely:
Be careful using date components when determining "today" vs "yesterday";
Use date formatters when trying to create the time strings or date/time strings; and
Use date components formatters when trying to build a string that represents the amount of time (or days) that has elapsed.

compare date from textfield

I have implemented two textFields From and To in ViewController.When the user selects the textField he is able to select the date from the calendar. The selected Date is stored in the TextField as
YYYY-MM-dd format.
And I have implemented a calculate button in ViewController.When the Two TextField are filled i need to do some work.
When the two textField are filled and the From TextField is greater , I want to display an alert when the From TextField date is Greater than To TextField.
How can i Compare it...?
Perfect solution
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *textFieldDateString1 = #"2016-07-14";
NSString *textFieldDateString2 = #"2016-07-15";
NSDate *date1 = [dateFormatter dateFromString:textFieldDateString1];
NSDate *date2 = [dateFormatter dateFromString:textFieldDateString2];
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
Printed Result is
date1 is earlier than date2
Date Comparision
Compare Two dates
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat: #"yyyy-MM-dd"];
NSDate * dt1 ;
NSDate * dt2 ;
dt1 = [df dateFromString: txt1.text];
dt2 = [df dateFromString: txt2.text];
NSComparisonResult result = [dt1 compare: dt2];
switch (result) {
case NSOrderedAscending:
NSLog(#"%# is greater than %#", dt2, dt1);
break;
case NSOrderedDescending:
NSLog(#"%# is less %#", dt2, dt1);
break;
case NSOrderedSame:
NSLog(#"%# is equal to %#", dt2, dt1);
break;
default:
NSLog(#"erorr dates %#, %#", dt2, dt1);
break;
}
Hope this will help you....
i think you are looking for this functionality..
NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
NSDateComponents *differenceComponents = [currentCalendar components:unitFlags fromDate:postdate toDate:[NSDate date] options:0];
NSInteger yearDifference = [differenceComponents year];
NSInteger monthDifference = [differenceComponents month];
NSInteger dayDifference = [differenceComponents day];
NSInteger hourDifference = [differenceComponents hour];
NSInteger minuteDifference = [differenceComponents minute];
i hope this will help you..
First you have to convert this two text field string date into NSDate object and and use compare: method of date to compare date.
NSString *dateString1 = #"2016-05-31"; //First text field value
NSString *dateString2 = #"2016-05-31"; //Second text field value
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
NSDate *date1=[dateFormatter dateFromString:dateString1];
NSDate *date2=[dateFormatter dateFromString:dateString2];
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}

selecting only working days from NSDate in objective c

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);

How to get NSDate start of previous month?

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);

How to compare the date which is come from server with [NSDate date] in ios?

I'm getting the date string from server in 01/02/2014 16:43:00 AM format, which is having GMT timeZone.
I've to compare that date with current date for live streaming. If the current date is lesser than that server date I've to show some alert which shows the correct live starting time. But I'm not able to compare them.
How to convert that server date string to date format and how to compare that date with current date ?
I'm using the following code :
NSString *DateFromServer = video.Eventutcstart;
NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
[dateFormatter1 setTimeZone:[NSTimeZone timeZoneWithName:tzName]];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
NSString *str = [dateFormatter1 stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter1 dateFromString:str];
NSDate *serverDate = [dateFormatter1 dateFromString: DateFromServer];
NSLog(#"currentDate %#", currentDate);
NSLog(#"serverDate %#", serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
output:
2014-01-03 11:30:25.346 VMS[955:70b] currentDate 2014-01-02 19:00:23 +0000
2014-01-03 11:30:32.088 VMS[955:70b] serverDate 2014-01-02 19:00:46 +0000
Please help me to solve this....
Please use below code. You were not setting timezone correctly:
NSString *DateFromServer = video.Eventutcstart;
NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
NSString *str = [dateFormatter1 stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter1 dateFromString:str];
NSDate *serverDate = [dateFormatter1 dateFromString: DateFromServer];
NSLog(#"currentDate %#", currentDate);
NSLog(#"serverDate %#", serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
For date comparison only,
You have two dates correctly obtained so can use :
int days1 = [currentDate timeIntervalSince1970] / 86400;
int days2 = [serverDate timeIntervalSince1970] / 86400;
if(days1==days2)
{
//do something;
}
else
{
//do something
}
Above code does not takes time in consideration and compares only year/month/day
For NSdate time comparison
unsigned int flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* component1 = [calendar components:flags fromDate:currentDate];
NSDateComponents* component2 = [calendar components:flags fromDate:serverDate];
NSDate* currentDateTimeOnly = [calendar dateFromComponents:component1];
NSDate* serverDateTimeOnly = [calendar dateFromComponents:component2];
NSComparisonResult result;
result = [currentDateTimeOnly compare:serverDateTimeOnly];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
try this code
if(result == NSOrderedAscending)
{
NSLog(#"alert message");
}
instead of this one
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
if you want to check both constraint with both date then you can use bellow code.
if(result == NSOrderedAscending){
NSLog(#"serverDate is in the future");
}else if(result == NSOrderedDescending){
NSLog(#"serverDate is in the past");
}else{
NSLog(#"Both dates are the same");
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString *a1=[def objectForKey:#"Currentdate"];
NSDate *now = [dateFormat dateFromString:a1];
NSDate * currentdate = [NSDate date];
NSString *nowstr=[dateFormat stringFromDate:currentdate];
NSDate *todaydate=[dateFormat dateFromString:nowstr];
NSLog(#"Now is %# and current date is %#",[def objectForKey:#"Currentdate"],nowstr);
NSComparisonResult result = [todaydate compare:now];
switch (result)
{
case NSOrderedAscending:
dateiswhich=-1;
NSLog(#"%# is in future from %#", currentdate, now);
break;
case NSOrderedDescending:
dateiswhich=1;
NSLog(#"%# is in past from %#", currentdate, now);
break;
case NSOrderedSame: dateiswhich=-1;
break;
default: NSLog(#"erorr dates %#, %#", currentdate, now); break;
}
use above code might be useful to you

Resources