How do you compare date objects to strings in Objective-C? - objective-c

I have an array of dates in this format:
date: 2012-01-02,2012-03-17,2012-04-09,2012-05-07,2012-06-04,2012-08-06,2012-10-29,2012-12-25,2012-12-26.
I want to compare the dates with today's date, but I need some help. This is my code.
NSArray *date =[dict12 objectForKey:#"ie_date_closed"];
NSLog(#"date:%#",date);
int i=date;
for (i=0; i<6; i++)
{
NSComparisonResult result = [todaydate compare:date[i]];
NSLog(#"result:%d",result);
}

Try below code:-
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy-MM-dd"];
for (NSString *arrDt in date){
if ([arrDt isEqualToString:[formatter stringFromDate:[NSDate date]]]){
NSLog(#"Equal Date");}}
Note:- You need to set the dateFormat according to array object dates.

Here is the code have a look at & try to implement your self using it :
for (i=0; i<[date count]; i++)
{
NSDateformatter *format = Define Your date Format Here
NSDate yourDate = [format dateFromString:[date objectAtIndex:i]];
If ([YourDate compare:[NSDate date]] == NSOrderedSame)
{
NSLog(#"Both Dates are same");
}
}
Note : I am not giving you whole readymade code but just for a hint so using it you can be able to implement what you want.
Hope this will help.

try it
NSDate *firstTime;
NSDate *nowTime;
NSDate *localDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = #"YYYY-MM-dd";
NSString *str = [dateFormatter stringFromDate:localDate];
NSArray *date =[dict12 objectForKey:#"ie_date_closed"];
NSLog(#"date:%#",date);
for (i=0; i<[date count]; i++)
{
NSString *openTime =[NSString stringWithFormate:"%#"[date objectAtindex:i]];
NSDateFormatter *dateComperFormatter1 = [[NSDateFormatter alloc] init];
[dateComperFormatter1 setTimeZone:[NSTimeZone systemTimeZone]];
[dateComperFormatter1 setDateFormat:#"YYYY-MM-dd"];
firstTime = [dateComperFormatter1 dateFromString:openTime];
nowTime = [dateComperFormatter1 dateFromString:str];
// NSComparisonResult result;
// // has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
//
// result = [nowTime compare:firstTime]; // comparing two dates
NSComparisonResult result = [nowTime compare:firstTime];
}

Related

UIDatePicker Order Format

I am new to ios development tried UIDatepicker format like day month date. I tried alot but not able to get, Can any one help ?
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]objectForKey:#"DatePickerViewController.selectedDate"];
storedDate = [dateFormat dateFromString:#"EE,MMMM dd"];
// add this check and set
if (storedDate == nil) {
storedDate = [NSDate date];
}
[self.pickerView setDate:storedDate animated:NO];
i need the above image format
First, get the saved date in string Format.
NSString *storedDate = [[NSUserDefaults standardUserDefaults]objectForKey:#"DatePickerViewControllerselectedDate"];
Then get the format in which the date is stored so that you can convert it to date.
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat=#"EEEE, MMMM dd";
Now you can convert the stored-date to date format and set in datepicker.
NSDate *sortedDateFormatted = [format dateFromString:storedDate];
[self.pickerView setDate:sortedDateFormatted animated:NO];
You need the date format ryt, Just try this
NSDate *now = [NSDate date];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat=#"EEEE, MMMM dd";
NSString * dateStr = [[format stringFromDate:now] capitalizedString];
NSDate *sortedDateFormatted = [format dateFromString:dateStr];
[self.pickerView setDate:sortedDateFormatted animated:NO];

"NSDate not an Objective-C object" error shows when run the application in IOS 7 in real device

NSDate object is working for iPhone, iPad when i ran the application in real devices. But when I run the application in iPad real device than it gives <not an Objective-C object> error. I tried to sort out it. but couldn't.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}
- (NSDate*) getDateFromJSON:(NSString *)dateString
{
// Expect date in this format "/Date(1268123281843)/"
int startPos = [dateString rangeOfString:#"("].location+1;
int endPos = [dateString rangeOfString:#")"].location;
NSRange range = NSMakeRange(startPos,endPos-startPos);
unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
NSTimeInterval interval = milliseconds/1000;
return [NSDate dateWithTimeIntervalSince1970:interval];
}
because of this issue i initialize the NSDate object and saw the date value. (NSDate *_Date = [NSDate alloc] init];) in here also gives same error? why is that? anyone faced this error ??
First off you can just remove this line:
NSDate *_Date = [NSDate alloc] init];
Since the next line just redeclares it, also you in the line you should remove you are missing a [.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
// Not needed since the line after it also declares the variable.
//NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}

List of days in Objective C

I wonder how could I make a list of days from MONDAY to SUNDAY...
I did it so:
- (NSString *) stringWithDayNameOf:(int)day {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"D"];
NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:#"%i", day]];
[dateFormat setDateFormat:#"eeee"];
NSString* outer = [dateFormat stringFromDate:date];
outer = [outer uppercaseString];
return outer;
}
for (int i = 1; i <= 7; i++) {
NSLog(#"DAY: %#", [self stringWithDayNameOf:i]);
}
But it displays days from today... How to fix that or make simpler?
Thanks!!
Use NSDateFormatter's weekdaySymbols and friends (for short names etc.)
%D is the format specifier for "day of year", not "day of week". There's no specifier for numerical day of week, since (as far as I know) no-one writes dates that way.
You need to create your date using NSDateComponents and then format that:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"eeee"];
NSCalendar * cal = [NSCalendar currentCalendar];
NSUInteger numWeekdays = [cal maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
NSDateComponents * comp = [[NSDateComponents alloc] init];
for( NSUInteger day = 1; day <= numWeekdays; day++ ){
[comp setWeekday:day];
[comp setWeek:0];
NSDate * date = [cal dateFromComponents:comp];
NSString * dayName = [dateFormat stringFromDate:date];
NSLog(#"%#", dayName);
}
Also, NSDateFormatter knows the names of the days of the week already: -[NSDateFormatter weekdaySymbols]. The first day of the week in the Gregorian calendar is Sunday.

Localized date (month and day) and time with NSDate

I want to be able to get the local date and time for wherever my app is run, based on the iPhone configuration. Specifically I need the date to be of format mm/dd or dd/mm (or dd.mm, mm.dd, dd-mm, mm-dd, etc) depending on the locale, and time is hh:mm. Is this possible with some combination of SDK methods?
Thanks!
I have modified the code so that it just takes the date and time out of the NSDate object with no changes:
NSDate* date = [NSDate date];
NSString* datePart = [NSDateFormatter localizedStringFromDate: date
dateStyle: NSDateFormatterShortStyle
timeStyle: NSDateFormatterNoStyle];
NSString* timePart = [NSDateFormatter localizedStringFromDate: date
dateStyle: NSDateFormatterNoStyle
timeStyle: NSDateFormatterShortStyle];
NSLog(#"Month Day: %#", datePart);
NSLog(#"Hours Min: %#", timePart);
Well, I believe the following code works for what I need:
NSString *dateComponents = #"yMMd";
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale currentLocale]];
NSArray *tmpSubstrings = [dateFormat componentsSeparatedByString:#"y"];
NSString *tmpStr;
NSRange r;
if ([[tmpSubstrings objectAtIndex:0] length] == 0) {
r.location = 1;
r.length = [[tmpSubstrings objectAtIndex:1] length] - 1;
tmpStr = [[tmpSubstrings objectAtIndex:1] substringWithRange:r];
} else {
r.location = 0;
r.length = [[tmpSubstrings objectAtIndex:0] length] - 1;
tmpStr = [[tmpSubstrings objectAtIndex:0] substringWithRange:r];
}
NSString *newStr = [[NSString alloc] initWithFormat:#"%# H:mm", tmpStr];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:newStr];
NSString *formattedDateString = [formatter stringFromDate:[NSDate date]];

iPhone simple method definition and calling the current date/time

I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.
But I'm getting a (null) value with NSLog.
Method:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [[NSDate alloc] init];
if (type==#"month") {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if (type==#"day") {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
//int setDate = theDate;
[dateFormat release];
return theDate;
}
[now release];
return NULL;
}
Calling the function to get value:
NSString *month = [self getNowDateMonth:#"month"];
NSLog(#"%#", month);
Am I going about this the right way?
First of all, compare the strings using [#"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.
Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].
To sum up, a suggested better version of this method would be:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [NSDate date];
if ([#"month" isEqualToString:type]) {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if ([#"day" isEqualToString:type]) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
return theDate;
} else {
return nil;
}
}
Also, there are a few other points that can be taken into consideration to improve this method:
do not use NSString as type; use an enum
do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method
You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.
See Date and Time Programming Guide for Cocoa.
Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.