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);
Related
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.
I'm getting Response from Webservices Date like "2012-08-17T00:00:00". I want to Display Date only like 17-08-2012. How Change Date format and Remove that time...
//String froms web service(ws)
NSString *stringFromWS =[NSString stringWithString:#"2012-08-17T00:00:00"];
//date formatter for the above string
NSDateFormatter *dateFormatterWS = [[NSDateFormatter alloc] init];
[dateFormatterWS setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date =[dateFormatterWS dateFromString:stringFromWS];
//date formatter that you want
NSDateFormatter *dateFormatterNew = [[NSDateFormatter alloc] init];
[dateFormatterNew setDateFormat:#"dd-MM-yyyy"];
NSString *stringForNewDate = [dateFormatterNew stringFromDate:date];
NSLog(#"Date %#",stringForNewDate);
also refer the link for more explanation
http://mobiledevelopertips.com/cocoa/date-formatters-examples-take-2.html
NSDate *today = [NSDate date];
NSLog(#"Date today: %#", today);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init] ;
dateFormat.dateFormat = #"dd-MM-yyyy";
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(#"Date: %#", dateString);
Also see the below date and time format styles
NSDateFormatterNoStyle
NSDateFormatterShortStyle
NSDateFormatterMediumStyle
NSDateFormatterLongStyle
NSDateFormatterFullStyle
You can set it like [dateFormat setDateStyle:NSDateFormatterShortStyle];
I have this ticks value "634758517020305000" which corresponds to 21st June 2012. I tried to convert the tick value into NSDate object like this:
NSString *str = #"634758517020305000";
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:
[[str substringWithRange:NSMakeRange(0, [str length])] intValue]]
dateByAddingTimeInterval:offset];
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:#"yy" withString:#"yyyy"];
[dateFormatter setDateFormat:fourDigitYearFormat];
}
// There you have it:
NSString *outputString = [dateFormatter stringFromDate:date];
But I got the output: 1/19/2038. If anyone knows where I am doing wrong, please let me know.
your Unix timestamps is wrong. it should be 1340236800
check your Unix timestamps Here
I am converting string to date and again to string. using following code
NSString *newDate =[NSString stringWithFormat:#"%#",[(Jobs *)[tableArray objectAtIndex:indexPath.row]Date]];
NSLog(#"New Date is %#",newDate);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy h:mm:ss a"];
NSDate *myDate = [dateFormat dateFromString:newDate];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSString *str = [dateFormat stringFromDate:myDate];
NSLog(#"DAte is %#",str);
It is returning date in simulator but not in iphone 4.3.3
please help
NSDateFormatter will return nil if it can't get the date from a string.
To see if it can parse the date add an other NSLog statement:
NSString *newDate =[NSString stringWithFormat:#"%#",[(Jobs *)[tableArray objectAtIndex:indexPath.row]Date]];
NSLog(#"New Date is %#",newDate);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy h:mm:ss a"];
NSDate *myDate = [dateFormat dateFromString:newDate];
NSLog(#"Date parsed: %#", myDate);
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSString *str = [dateFormat stringFromDate:myDate];
NSLog(#"DAte is %#",str);
But since you only want the firs part of the string why not just substring it.
NSString *str = [newDate substringToIndex:10];
and what is returned here:
NSString *newDate =[NSString stringWithFormat:#"%#",[(Jobs *)[tableArray objectAtIndex:indexPath.row]Date]];
it the property Date already a NSDate ?, can you show your .h file for Jobs?
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.