Comparing two dates for daily reward in iOS game - iphone

I was implementing a 'daily reward' method in order to give some coins every day in my game.
I have a json that contains the actual date and time.
The issue is that I don't know how to compare the dates.
Here is my code -
#implementation ItemRewardManager
+(NSDate *)dateFromUTCTimeStamp:(NSString *)dateString{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSDate *myDate = [df dateFromString: dateString];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[df setTimeZone:gmt];
[[NSUserDefaults standardUserDefaults] setObject:myDate forKey:#"lastDatePlayed"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)getData
{
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:dateUrl]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSArray *keys = [jsonObjects allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(#"%# is %#",key, [jsonObjects objectForKey:key]);
}
}
+(void)dailyReward{
NSLog(#"llega al daily");
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HH:mm:ss zzz"];
NSDate *now = [NSDate date];
NSString *dateString = [dateFormat stringFromDate:now];
if([[[NSUserDefaults standardUserDefaults] objectForKey:#"lastDatePlayed"] isEqualToString: dateString])
{
NSLog(#"Actual date is the same as json date");
UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:nil
message:#"You have win 5 coins! Come back tomorrow for more."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] autorelease];
[alert show];
return;
}
}
#end
So, when I open my app and call this method, my app crashes for some reasone.
I think the problem might be on the comparison of the two dates.
Can someone tell me if there is something wrong?

Use following.
if ([date1 compare:date2]==NSOrderedSame)
date1 and date2 are NSdate objects.

NSDate has methods for comparing dates.
Here they are:
isEqualToDate: Returns a Boolean value that indicates whether a given
object is an NSDate object and exactly equal the receiver.
- (BOOL)isEqualToDate:(NSDate *)anotherDate
laterDate: Returns the later of the receiver and another given date.
- (NSDate *)laterDate:(NSDate *)anotherDate
earlierDate: Returns the earlier of the receiver and another given
date.
- (NSDate *)earlierDate:(NSDate *)anotherDate

Try like this. It may help you
NSDate *now = [NSDate date]; // current date
NSDate *newDate = [dateFormat dateFromString:[[NSUserDefaults standardUserDefaults] objectForKey:#"lastDatePlayed"]]; // server date
NSComparisonResult result;
result = [now compare:newDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"now is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else
NSLog(#"Both dates are same");

Use this code.
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy"];
NSDate *ServerDate = [dateFormatter1 dateFromString:#"03/01/2013"];
[dateFormatter1 release];
NSTimeInterval interval = [date timeIntervalSinceDate:ServerDate];
int diff=interval/1440;
This is implemented code.

Related

adding events to default calendar in iPhone

i am trying to add the event to iPhone default calendar and the code is as follows
NSMutableString *startDateString = [NSMutableString stringWithString:#"11/20/2012 10:00 AM"];
NSMutableString *endtDateString = [NSMutableString stringWithString:#"11/20/2012 5:00 PM"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"MM-dd-yyyy HH:mm a"];
NSDate * startDate = [[NSDate alloc]init];
startDate = [dateFormatter dateFromString:startDateString];
NSDate *endDate = [[NSDate alloc]init];
endDate = [dateFormatter dateFromString:endtDateString];
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = #"TEST";
event.startDate = startDate;
event.endDate = endDate;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
[startDate release];
[endDate release];
if(!err)
{
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:#"TEST" message:#"Event Added successfully " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertview show];
[alertview release];
}
NSLog(#"error is %#",err);
}
the event is successfully adding but the problem is its not adding to event start date its just adding to jan 1st 2001 date all the events are adding to the same date only .
can any one please help me where i am getting wrong & i am using the iPhone 4s & iPhone 3gs with 5.1.1 version.
Thanks in advance .
Set DateFormat to dateFormatter like this:
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
Note: yourdateString should be according to dateFormatter

iPhone : Unable to convert date from string

I am trying to convert string into NSDate using following code.
NSString *old = [[NSUserDefaults standardUserDefaults] valueForKey:#"OLD_DATE"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *oldDate = [formatter dateFromString:old];
NSLog(#"Old Date : %#",oldDate);
I am setting OLD_DATE as following :
NSDate *oldDate = [NSDate date];
NSString *old = [[NSString stringWithFormat:#"%#",oldDate] retain];
[[NSUserDefaults standardUserDefaults] setObject:old forKey:#"OLD_DATE"];
But I am getting null in the NSLog(#"Old Date : %#",oldDate); :(
I found many similar links with the same code and works fine for them.
So what could be problem with my code ?
Don't covert the date to string:
NSDate *oldDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:oldDate forKey:#"OLD_DATE"];
To read out the date just:
NSDate *old = [[NSUserDefaults standardUserDefaults] objectForKey:#"OLD_DATE"];
There really should not be any reason to concert the date to a string before saving to in the NSUserDefaults.
But if you want to concert the string back to a date you will need the correct format.
A NSDate descrption would be something like 2011-11-11 12:58:36 +0000
NSString *old = [[NSUserDefaults standardUserDefaults] valueForKey:#"OLD_DATE"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss z"];
NSDate *oldDate = [formatter dateFromString:old];
NSLog(#"Old Date : %#",oldDate);

how to store selected value and show on cell when application run again in iphone

I have a date picker view controller where I select the date. When I come back I can see the selected date on the tableview cell. So far, this all works properly. I face a problem when I exit the application and run it again, I can't see the last selected value in the cell. How can I do this?
If the user exits the application, they should be able to see the last selected date on the cell so that they can review or use that date.
This is my date controller class code .m file
- (void)viewDidLoad
{
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 0, 0)];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.minimumDate = [NSDate date];
[self.view addSubview:datePicker];
[super viewDidLoad];
}
-(void)DateChangeForFinalPayMent
{
//remove time
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int comps = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:comps fromDate:[datePicker date]];
NSDate *dateSelected = [gregorian dateFromComponents:dateComponents];
NSLog(#"dateSelected:%#",dateSelected);
[gregorian release];
if ([selectionData type] == 0)
[selectionData setFromDateSelected:dateSelected];
else
[selectionData setToDateSelected:dateSelected];
}
-(IBAction)click
{
[self DateChangeForFinalPayMent];
[self.navigationController popViewControllerAnimated:YES];
}
here is my firstview controller where i show my selected value date on cell
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSString* fromDate = [dateFormat stringFromDate:app.selectionData.fromDateSelected];
NSString* toDate = [dateFormat stringFromDate:app.selectionData.toDateSelected];
if ([indexPath row] == 0 && [indexPath section] == 1)
{
cell.textLabel.text=#"From Date";
cell.detailTextLabel.text=fromDate;
}
if ([indexPath row] == 1 && [indexPath section] == 1)
{
cell.textLabel.text=#"To Date";
cell.detailTextLabel.text=toDate;
}
Can anybody suggest how to store the value and show it to the user when they open the application again.
PFB code to save and reteive the date value from the User defaults
//Storing date value to the user defaults
NSDate * selectedDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the date format.. u can choose different one based on ur requirement
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
//String from the NSDate
NSString *pStrDate = [dateFormatter stringFromDate:selectedDate];
//Save date value to the user defaults
[[NSUserDefaults standardUserDefaults] setObject: pStrDate forKey:#"date"];
[[NSUserDefaults standardUserDefaults] synchronize];
Retrieving date from the user defaults:
NSDate *dateFromString = [[NSDate alloc] init];
NSString *savedDateVaue=nil;
if([[NSUserDefaults standardUserDefaults] objectForKey:#"date"]!=nil)
{
savedDateVaue=[[NSUserDefaults standardUserDefaults] objectForKey:#"date"];
dateFromString = [dateFormatter dateFromString:savedDateVaue];
}

From string with locale to date on iphone sdk

I trying to find a way to convert a string into a date with a given locale identifier.
I have for example an italian date (locale: it_IT) I want to convert into a valid date object.
NSDate *GLDateWithString(NSString *string, NSString *localeIdentifier) {
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[formatter setLocale:locale];
[locale release];
NSDate *date = [formatter dateFromString:string];
[formatter release];
return date;
}
this code does not work, the date is nil.
I can't figure out how I should use the locale setting for my purpose.
The solution is to use getObjectValue:forString:range:error: method of NSDateFormatter and set the correct date and time style ad follow:
- (NSDate *)dateWithString:(NSString *)string locale:(NSString *)localeIdentifier {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setDateStyle:NSDateFormatterShortStyle];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[formatter setLocale:locale];
[locale release];
NSDate *date = nil;
NSRange range = NSMakeRange(0, [string length]);
NSError *error = nil;
BOOL converted = NO;
converted = [formatter getObjectValue:&date forString:string range:&range error:&error];
[formatter release];
return converted? date : nil;
}
example:
NSString *italianDate = #"30/10/2010";
NSString *italianLocale = #"it_IT";
NSDate *date = [myCustomFormatter dateWithString:italianDate locale:italianLocale];
I struggled with German formats as well sometime ago and solved the problem by supplying my own formatting string:
[formatter setDateFormat:#"dd.MMM.yyyy HH:mm:ss"];
Then:
[dateFormatter dateFromString:#"01.Dez.2010 15:03:00"];
will get a correct NSDate.

NSDateFormater from NSMutableArray value

I store some dates in my NSMutableArray, I want to retrieve them and change the format.
For the moment I do this:
NSDate *myDate = [self.dates objectAtIndex:0];
NSLog(#"myDate:%#", myDate); // 2010-03-02
NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateFormat:#"MMMM d YYYY"];
NSString *newDate = [formatDate stringFromDate:myDate];
NSLog(#"newDate: %#", newDate); // NULL
the result for newDate is NULL, and I want it to be something like that: "March 3, 2010"
thanks,
That works for me, but I replaced the first line with:
NSDate *myDate = [NSDate date];
My output:
2010-03-02 19:29:08.045 app[11464:a0f] myDate:2010-03-02 19:29:08 -0800
2010-03-02 19:29:08.048 app[11464:a0f] newDate: March 2 2010
My best guess is that [self.dates objectAtIndex:0] isn't returning what you want it to.
Since your dates array contains strings, you have to convert the string to an NSDate and then you can re-convert the date to the format you want.
NSDateFormatter *strToDateFmt = [[NSDateFormatter alloc] init];
[strToDateFmt setDateFormat:#"yyyy-MM-dd"];
NSDate *myDate = [strToDateFmt dateFromString:[self.dates objectAtIndex:0]];
[strToDateFmt release];
NSLog(#"myDate:%#", myDate);
NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateFormat:#"MMMM d YYYY"];
NSString *newDate = [formatDate stringFromDate:myDate];
[formatDate release];
NSLog(#"newDate: %#", newDate);