Another NSDateFormatter issue - ios6

Having gone through the documentation, it would seem the following case should work, but the result is always nil. (This is for iOS sdk 6)
NSString *releaseDate = #"2012-10-22T00:00:00-07:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date = nil;
[dateFormatter setDateFormat:#"yyyy-MM-ddTHH:mm:ss-ZZZZZ"];
date = [dateFormatter dateFromString:releaseDate];
NSLog(#"Result date: %#", date); // Logs "(null)"
Any insights?
Thanks in advance for any help.

How about you try this. If your date string is unlocalized as I am guessing, even Apple suggests you could use something like this:
struct tm tmDate;
const char *formatString = "%Y-%m-%dT%H:%M:%S%z";
strptime_l(releaseDate, formatString, & tmDate, NULL);
date = [NSDate dateWithTimeIntervalSince1970: mktime(& tmDate)];
NSLog(#"Result date: %#", date);
Your release date will have to be a C string though, as in const char *releaseDate = "2012-10-22T00:00:00-07:00";, which you can get also from the UTF8String method of NSString.

Ok. A bit of re-reading of the docs revealed my misunderstandings:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *releaseDate = #"2012-10-22T00:00:00-07:00";
NSDate *date = nil;
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
date = [dateFormatter dateFromString:releaseDate];
NSLog(#"Result date: %#", date);
NSLog(#"Result string: %#", [dateFormatter stringFromDate:date]);
The "T" had to be enclosed in apostrophes and the "ZZZZZ" for time zone already accounts for the "-" so it had to be removed.
Now it works as expected.

Related

Xcode Count of like items in Array

I have a list of years in an Array. Which I would like to output as a list of the counts.
For example:
NSArray *years = #[#"2012", #"2014", #"2009", #"2014", #"2010", #"2014", #"2009"];
I am looking to turn this into something like this in a Dictionary.
Year = 2012, Count = 1
Year = 2014, Count = 3
Year = 2009, Count = 2
Year = 2010, Count = 1
Thanks
NSArray *years = [NSArray arrayWithObjects:#"2012", #"2014", #"2009", #"2014", #"2010", #"2014", #"2009", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:years];
for (id item in set)
{
NSLog(#"Name=%#, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
I suggest you invest some time into reading a book about Cocoa's features.

Trying to get Weekday using NSDateComponents but weekday always the same

I'm trying to obtain the day of the week using the code below with a variable NSString. Whatever value I use the weekday always comes back as 2. What am I doing wrong?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"EEE, dd MMM yyyy"];
NSString *stringDate = #"23/05/2013";
NSDate *dateStr = [dateFormatter dateFromString:stringDate ];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateStr];
gWeekday = [weekdayComponents weekday];
The date format does not match your string. With
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *stringDate = #"23/05/2013";
you get the correct result.

Parse large string & replace the parsed string value with new value in iOS 6+

In my app I want to follow below steps to get the finalized string.
My message format is given below
message <br/><br/> On {date_time_stamp} sender_name wrote <br/><br/>
Let say my message string is as below
Hello developers <br/><br/> On {2013-02-28 05:00:33} Bob wrote <br/><br/>
Hello World <br/><br/> On {2013-02-27 08:35:33} Jack wrote <br/><br/>
Hello Apple <br/><br/> On {2013-02-26 04:10:44} Tom wrote <br/><br/>
Now I need to follow below steps
Get the all dates in message one by one
Convert it from GMT time zone to local time zone
Replace GMT dates in message with local date time
Finally replace "breakline with \n" & remove curly braces from message.
I have the below code
-(void)parseMessageBody:(NSString*)msg
{
NSRange openBracket = [msg rangeOfString:#"{"];
NSRange closeBracket = [msg rangeOfString:#"}"];
NSRange numberRange = NSMakeRange(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [msg substringWithRange:numberRange];
NSLog(#"Parsed string: %#",numberString);
}
-(NSString*)formattedMessageFromString:(NSString*)msg
{
NSString *formattedMessage = #"";
formattedMessage = [msg stringByReplacingOccurrencesOfString:#"<br/>" withString:#"\n"];
return formattedMessage;
}
-(NSString*)getLocalDateFromUTCDateString:(NSString*)utcDateString
{
NSDateFormatter *serverDateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[serverDateFormatter setTimeZone:sourceTimeZone];
[serverDateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromServer = [serverDateFormatter dateFromString:utcDateString];
DLog(#"UTC date From SERVER: %#",dateFromServer);
NSDateFormatter *localDateFormatter = [[NSDateFormatter alloc] init];
[localDateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeZone* localTimeZone = [NSTimeZone systemTimeZone];
[localDateFormatter setTimeZone:localTimeZone];
NSString *localDate = [localDateFormatter stringFromDate:dateFromServer];
DLog(#"Converted Local DAte : %#",localDate);
return localDate;
}
I am not able perform steps 1 & 3 to get all the dates in message & replace it with local date time.
Also message can grow over the time. So parsing needs to be fast.
Can anybody tell me how can I get all the dates in message & replace it with converted date ?
Any kind of help is highly appreciated. Thanks in advance.
Finding and replacing the dates can be done with regular expressions:
NSString *msg = #"Hello developers <br/><br/> On {2013-02-28 05:00:33} Bob wrote <br/><br/>\n"
"Hello World <br/><br/> On {2013-02-27 08:35:33} Jack wrote <br/><br/>\n"
"Hello Apple <br/><br/> On {2013-02-26 04:10:44} Tom wrote <br/><br/>\n";
NSMutableString *replacedMsg = [msg mutableCopy];
NSString *pattern = #"\\{(.+?)\\}"; // Pattern for { ... }
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
__block int offset = 0;
[regex enumerateMatchesInString:msg options:0 range:NSMakeRange(0, [msg length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange range0 = [result range]; // range including { }
NSRange range1 = [result rangeAtIndex:1]; // range excluding { }
range0.location += offset;
range1.location += offset;
NSString *oldDate = [replacedMsg substringWithRange:range1];
NSString *newDate = [self getLocalDateFromUTCDateString:oldDate];
if (newDate != nil ) {
[replacedMsg replaceCharactersInRange:range0 withString:newDate];
offset += [newDate length] - range0.length;
}
}];
NSLog(#"%#", replacedMsg);
Output (my local timezone is GMT+01):
Hello developers <br/><br/> On 2013-02-28 06:00:33 Bob wrote <br/><br/>
Hello World <br/><br/> On 2013-02-27 09:35:33 Jack wrote <br/><br/>
Hello Apple <br/><br/> On 2013-02-26 05:10:44 Tom wrote <br/><br/>

dateFormatter is returning January as the month when the data in the json array is February

I am trying to convert the date stored in my json array as yyyy-mm-dd (i.e. 2013-02-14) to Day, date month year (i.e. Thu 14 Feb 2013) and for some reason it is converting the month to January, can anyone tell me why please? Thank you.
NSString *endDate = [info objectForKey:#"EndDate"];
[dateFormatter setDateFormat:#"yyyy-mm-dd"];
NSDate *edate = [dateFormatter dateFromString:endDate];
[dateFormatter setDateFormat:#"EEE d MMM yyyy"];
NSString *convertedEndDate = [dateFormatter stringFromDate:edate];
The format for the month is "MM", not "mm" (which is for minutes):
NSString *endDate = #"2013-02-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *edate = [dateFormatter dateFromString:endDate];
[dateFormatter setDateFormat:#"EEE d MMM yyyy"];
NSString *convertedEndDate = [dateFormatter stringFromDate:edate];
NSLog(#"%#", convertedEndDate);
Output:
Thu 14 Feb 2013

predicateForEventsWithStartDate:endDate:calendars: EKEventStore doesn't work

i have saved 28 EKEvent in a EKCalendar in this range date: 2012-01-01 and 2013-01-18, the EKEvent are all stored and i can see it in the iOS Calendar on iCloud, then i want retrieve all this EKEvent in the range 2012-01-01 and 2013-01-18 and i use this method of EKEventStore:
predicateForEventsWithStartDate:endDate:calendars:
that is a NSPredicate to fetch event in the calendar, i pass with start date 2012-01-01 and with endDate:2013-01-18 so the array that return me with the EKEvent have only 8 element, so my question is why it doesn't find me all 28 event? what i wrong?
EDIT:
this is the complete code i use:
NSDate* sourceDate2 = [dateFormat dateFromString:#"2012/01/01"];
NSTimeZone* sourceTimeZone2 = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone2 = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset2 = [sourceTimeZone2 secondsFromGMTForDate:sourceDate2];
NSInteger destinationGMTOffset2 = [destinationTimeZone2 secondsFromGMTForDate:sourceDate2];
NSTimeInterval interval2 = destinationGMTOffset2 - sourceGMTOffset2;
NSDate* destinationDate2 = [[NSDate alloc] initWithTimeInterval:interval2 sinceDate:sourceDate2];
NSTimeInterval time2 = floor([destinationDate2 timeIntervalSinceReferenceDate] / 86400.0) * 86400.0;
NSDate *startDate = [NSDate dateWithTimeIntervalSinceReferenceDate:time2];
then i use the same code for create the 2013-01-18 date that is the endDate, then i do this:
EKEventStore *eventStore = [[EKEventStore alloc] init];
NSPredicate *predicateEvent = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:[eventStore calendarsForEntityType:EKEntityTypeEvent]];
NSArray *eventArray = [eventStore eventsMatchingPredicate:predicateEvent];
the eventArray contains only 8 elements...and where are the other 20? please i'm going crazy someone can help me?
On your device, go to: Settings > Mail, Contacts, Calendars, and under the Calendars sub-section go to Sync > All Events. Not just events from the past 30, 60 days, etc.

Resources