ALAsset timestamp returns wrong date - iphone

I am trying to get the timestamp of images, I can get the correct latitude and longitude values, but the timestamp always returns the current time, not the EXIF time of the image.
ALAssetsLibraryAssetForURLResultBlock resultsBlock = ^(ALAsset *asset) {
CLLocation *imageLoc = [asset valueForProperty:ALAssetPropertyLocation];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/YY HH:mm:ss"];
NSString *trailTime = [formatter stringFromDate:imageLoc.timestamp];
NSLog(#"---+++ image TimeStamp: %#", trailTime);
[formatter release];
Any help appreciated, thanks

You will need to get the date using ALAssetPropertyDate key.
NSDate * date = [asset valueForProperty:ALAssetPropertyDate];
/* Use the `NSDateFormatter` instance to print the date */

OK I found the answer
What gave me the entire metadata in dictionary format was:
NSDictionary *metadata = asset.defaultRepresentation.metadata;
//Hope this helps others.

It seems like you're fetching location to get the date. you should be doing something like the following:
ALAssetsLibrary *assetsLib = [[ALAssetsLibrary alloc] init];
[assetsLib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
//If you'd want to directly fetch from it's external property, which seems more appropriate.
NSDate *date = [result valueForProperty:ALAssetPropertyDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:#"dd-mm-yyyy hh:mm:ss ZZZ"];
NSString *stringDate = [dateFormatter stringFromDate:date];
//If you'd want to fetch the date from metaData
ALAssetRepresentation *assetRep = [result defaultRepresentation];
NSDictionary *dictionaryOfMetaData = [assetRep metadata];
NSLog(#"dictionary:%# \n \
date:%# \n \
StringDate:%#", [[dictionaryOfMetaData valueForKey:#"{TIFF}"] valueForKey:#"DateTime"],
date,
stringDate);
}];
}
failureBlock:^(NSError *error) {
//Handle Error!
}];

Related

How to convert the NSString of format (2013-07-25T06:15:33.180-04:00) to NSDate?

How to convert the NSString of format (2013-07-25T06:15:33.180-04:00) to NSDate?
I am trying to convert using the following code
NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
[rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[rfc3339TimestampFormatterWithTimeZone setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss ZZZ"];
NSDate *theDate = nil;
NSError *error = nil;
if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
NSLog(#"Date '%#' could not be parsed: %#", dateString, error);
}
NSString *strDate = [rfc3339TimestampFormatterWithTimeZone stringFromDate:theDate];
return strDate;
Please help me
try like this,i hope you'l succeed..
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"];
NSDate *date = [dateFormatter dateFromString:#"2013-07-25T06:15:33.180-04:00"];//chnage symbal here.
NSLog(#"%#",date);

Comparing two dates for daily reward in iOS game

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.

issue in Changing date formate

i have one array of string something like below
newlymadeArray(
"03/05/2013",
"09/22/2013",
"03/02/2013",
"03/02/2013",
"08/22/2013",
"11/02/2013",
"07/08/2013",
"08/31/2013",
"05/13/2013",
"07/11/2013",
"10/07/2013",
"02/20/2013"
)
current formate is MM/dd/yyyy
i want to change it to dd/MM/yyyy
i am using following code for this
NSLog(#"_newlymadeArray%#",_newlymadeArray);
//logic for changing date formate
for( int i=0; i<_newlymadeArray.count; i++){
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:#"dd/MM/yyyy"];
NSDate *old = [dateFormatter1 dateFromString:[_newlymadeArray objectAtIndex:i]];
NSLog(#"old %#",old);
NSString *old1 =[dateFormatter1 stringFromDate:old];
NSDate *new = [dateFormatter2 dateFromString:old1];
NSLog(#"new %#",new);
NSString *string = [dateFormatter2 stringFromDate:new];
NSLog(#"string %#",string);
[_convertedBdates addObject:string];
}
NSLog(#"_convertedBdates%#",_convertedBdates);
this is what im getting as output
old 2013-03-04 18:30:00 +0000
new 2013-05-02 18:30:00 +0000
string 03/05/2013
old 2013-09-21 18:30:00 +0000
new (null)
string (null)
] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
my questions are why old get printed 2013-03-04 instead of 05/03/2013
at the end of first time loop it gets printed 03/05/2013 instead of 05/03/2013
and when loop is running second time it gets null value in new so thats why adding null value in array program get crashed
plz tell me what im doing wrong ?
This is never going to be appropriate:
NSString *old1 =[dateFormatter1 stringFromDate:old];
NSDate *new = [dateFormatter2 dateFromString:old1];
You're saying, "Format a date using one formatter... and then parse it using a different one."
You've already parsed the value which was in the old format. You now need to format it in the new formatter.
I'm not an Objective-C developer, but I suspect you just want:
NSDate *date = [dateFormatter1 dateFromString:[_newlymadeArray objectAtIndex:i]];
NSString *string = [dateFormatter2 stringFromDate:date];
[_convertedBdates addObject:string];
Note how there's only one date involved, but two strings (the original format and the new format).
Also note that there's no need to create a new pair of formatters on each iteration of the loop. Create them before the loop and reuse them:
NSDateFormatter *oldFormatter = [[NSDateFormatter alloc] init];
[oldFormatter setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *newFormatter = [[NSDateFormatter alloc] init];
[newFormatter setDateFormat:#"dd/MM/yyyy"];
for (int i = 0; i < _newlymadeArray.count; i++) {
NSDate *date = [oldFormatter dateFromString:[_newlymadeArray objectAtIndex:i]];
NSString *string = [newFormatter stringFromDate:date];
[_convertedBdates addObject:string];
}
(You may also want to check whether date is null within the loop, to handle bad data, of course.)
Try this one:
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:#"dd/MM/yyyy"];
for( int i=0; i<_newlymadeArray.count; i++){
NSDate *old = [dateFormatter1 dateFromString:[_newlymadeArray objectAtIndex:i]];
NSLog(#"old %#",old);
if (old) {
NSString *newDateString = [dateFormatter2 stringFromDate:old];
NSLog(#"new %#",newDateString);
[_convertedBdates addObject:newDateString];
}
}
[dateFormatter1 release];
[dateFormatter2 release];
NSDateFormatter *fromDateFormatter = [[NSDateFormatter alloc] init];
[fromDateFormatter setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *toDateFormatter = [[NSDateFormatter alloc] init];
[toDateFormatter setDateFormat:#"dd/MM/yyyy"];
for (NSString *dateString in newlyMadeArray)
{
NSDate *date = [fromDateFormatter dateFromString:dateString];
NSString *newDateString = [toDateFormatter stringFromDate:date];
[_convertedBdates addObject:newDateString];
}
First you should convert the string "MM/dd/yyyy" to "dd/MM/yyyy".
for( int i=0; i<_newlymadeArray.count; i++){
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:#"dd/MM/yyyy"];
NSDate *old = [dateFormatter1 dateFromString:[_newlymadeArray objectAtIndex:i]];
NSLog(#"old %#",old);
NSArray *arr = [[_newlymadeArray objectAtIndex:i] componentsSeparatedByString:#"/"];
NSString *old1 = [NSString stringWithFormat:#"%#/%#/%#",[arr objectAtIndex:1],[arr objectAtIndex:0],[arr objectAtIndex:2]];
NSDate *new = [dateFormatter2 dateFromString:old1];
NSLog(#"new %#",new);
NSString *string = [dateFormatter2 stringFromDate:new];
NSLog(#"string %#",string);
[_convertedBdates addObject:string];
}

Change NSDateFormatter For Dates in Array?

Right now my dates look like this:`2011-01-01 5:45:23 +0000
I want them to look like this: 2011-01-01 00:00:00 +0000 (notice how everything is 00 beside the date, month, and year).
I have an array of NSdates which is fetched from this code:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES]; //set to YES if you only want unique values of the property
[request setPropertiesToFetch :[NSArray arrayWithObject:#"timeStamp"]]; //name(s) of properties you want to fetch
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
NSArray *data = [objects valueForKey:#"timeStamp"];
NSLog(#"The content of data is%#", data);
I want to remove daylight savings and have 0:00:00 for the time aspect of each date, thus I need this NSDateFormatter method:
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"]; // e.g., set for mysql date strings
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSString* mysqlGMTString = [formatter stringFromDate:[NSDate date]];
So how can I combine the two to work together?
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
for (NSDate *d in data) {
NSString* mysqlGMTString = [formatter stringFromDate:d];
// ...
}
[formatter release];
Since your requirement is to have strings in the data array, this code should suit your purpose.
NSMutableArray * resultsArray = [NSMutableArray array];
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSUInteger flags = ( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit );
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDate * date = [gregorian dateFromComponents:[gregorian components:flags fromDate:obj]];
[resultsArray addObject:[formatter stringFromDate:date]];
}];
resultsArray will contain the strings that you need. Now you can have data referring to the object
As for the search with a date part,
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
// Assuming `data` is from the code above & the date is in `00:00:00 +0000` form.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSString * dateString = [formatter stringFromDate:d];
if ( [data containsObject:dateString] ) {
// Push object to detail view??
}
}
Also use yyyy instead of YYYY. They are not the same.

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.