NSDate from NSString - ios4

I need to convert string in the format of "Jan 2nd, 2011 11:38am" in to corresponding NSDate.
I used following code to convert the string to date.
+ (NSDate *) dateFromString: (NSString *) dateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
return dateFromString;
}
but it returns nil.
Can any one please help me with this?

+ (NSDate *) dateFromString: (NSString *) dateString
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}

You have to do like this
NSDate *dateFromString = [[dateFormatter dateFromString:dateString] retain];
and in return statement
return [dateFromString autorelease];
or
in place of [dateFormatter release];
you have to use
[dateFormatter autorelease];

+(NSDate *)dateFromString:(NSString *)dateString
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:#"EEE, d MMM yyyy HH:mm:ss zzzz"];
NSDate *date = [dateFormatter dateFromString:dateString];
return date;
}

Related

Fetching Sorted Array based on NSDate from Core Data Entity in iOS9 using Objective C

I am using core data for storing alarm details (AlarmDate is stored as Date type), while fetching all alarms i have used NSSortDescripotor as
NSManagedObjectContext *managedObjectContext = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Alarm"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"AlarmDate"
ascending:YES];
NSArray *sortDescriptors = #[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSArray *arrayForAllAlarms = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
for above it is returning the alarms in sorted order, but i need it should also consider the AM and PM while sorting
Example:
if alarms date are added like:
11.00 pm,
01.30 am and
10.00 pm
it should return:
01.30 am
10.00 pm and
11.00 pm
Thank you!
Find Solution, Written custom sorting for existing fetched array as following:
NSArray *arrayForAllAlarmsSorted = [arrayForAllAlarms sortedArrayUsingComparator:
^(Alarm *alarmObject1, Alarm *alarmObject2) {
NSDate *dateForAlarm1 = [NSDate date:alarmObject1.alarmDateTime withFormat:#"hh:mm a"];
NSDate *dateForAlarm2 = [NSDate date:alarmObject2.alarmDateTime withFormat:#"hh:mm a"];
return [dateForAlarm1 compare:dateForAlarm2];
}];
And the NSDate Category function written as:
+(NSDate *)date:(NSDate *)date withFormat:(NSString *)format {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
dateFormatter.dateFormat = format;
NSDate *newDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:date]];
return newDate;
}

Convert NSDate to NString

I have the date format like this: "2014-01-04 10:46:58 +0000". I want to
convert it into format like this HH:MM:SS.
Anyone could solve my problem here?
Thanks in advance.
use
NSString *dateString = #"2014-01-04 10:46:58 +0000";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter1 dateFromString:dateString];
[dateFormatter1 release];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:#"HH:mm:ss"];
NSString *strDate = [dateFormatter2 stringFromDate:[NSDate dateFromString ]];
NSLog(#"%#", strDate);
[dateFormatter2 release];

Core Data: Not saving

I'm having trouble saving to one variable letsMeet.startTimeLabel. Right after selecting NSLog shows the correct Value, however, after I save to another variable (letsMeet.endTimeLabel), letsMeet.startTimeLabel changes to (NULL). Below is the code:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
switch (actionSheet.tag)
{
case 1:
{
if (buttonIndex == 0)
{
UIDatePicker *startDatePicker = (UIDatePicker *)[actionSheet viewWithTag:kDatePickerTag1];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd"];
NSDate *selectedDate = [startDatePicker date];
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:#"EEEE"];
NSDate *selectedDay= [startDatePicker date];
NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
[monthFormatter setDateFormat:#"MMMM"];
NSDate *selectedMonth = [startDatePicker date];
NSString *date = [[NSString alloc] initWithFormat:#"%#", [dateFormatter stringFromDate:selectedDate]];
DateLabel.text = date;
[letsMeet setDateLabel:date];
NSString *month = [[NSString alloc] initWithFormat:#"%#", [dayFormatter stringFromDate:selectedMonth]];
MonthLabel.text = month;
[letsMeet setMonthLabel:month];
NSString *day = [[NSString alloc] initWithFormat:#"%#", [monthFormatter stringFromDate:selectedDay]];
DayLabel.text = day;
[letsMeet setDateLabel:day];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat: #"h:mm a"];
NSDate *selectedStartTime = [startDatePicker date];
NSString *startTime = [[NSString alloc] initWithFormat:#"%#", [timeFormatter stringFromDate:selectedStartTime]];
StartTimeLabel.text = startTime;
[letsMeet setStartTimeLabel:startTime];
NSError *error = nil;
if (![managedObjectContext save:&error]){
NSLog(#"Error Saving");
}
}
NSLog (#"This is the StartTime after selecting %#", letsMeet.startTimeLabel);
}
break;
case 2:
{
if (buttonIndex == 0)
{
UIDatePicker *endTimePicker = (UIDatePicker *)[actionSheet viewWithTag:kDatePickerTag2];
NSDateFormatter *endTimeFormatter = [[NSDateFormatter alloc] init];
[endTimeFormatter setDateFormat: #"h:mm a"];
NSDate *endSelectedTime = [endTimePicker date];
NSString *endTime = [[NSString alloc] initWithFormat:#"%#", [endTimeFormatter stringFromDate:endSelectedTime]];
EndTimeLabel.text = endTime;
[letsMeet setEndTimeLabel:endTime];
NSLog (#"This is the EndTime %#", letsMeet.endTimeLabel);
NSLog (#"This is the StartTime after selecting BOTH %#", letsMeet.startTimeLabel);
}
else if (buttonIndex == 1)
{
EndTimeLabel.text = #"Whenever";
[letsMeet setEndTimeLabel:EndTimeLabel.text];
}
NSError *error = nil;
if (![managedObjectContext save:&error]) {
}
}break;
// Handle the error.
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *destinationViewController = segue.destinationViewController;
NSLog (#"Prepare For Segue StartTime %#", letsMeet.startTimeLabel);
NSLog (#"Prepare For Segue EndTime%#", letsMeet.endTimeLabel);
}
Here is the log:
2013-02-20 21:38:24.253 AppointmentTime[3129:c07] This is the StartTime after selecting 9:30 AM
2013-02-20 21:38:32.325 AppointmentTime[3129:c07] This is the EndTime 12:15 PM
2013-02-20 21:38:32.325 AppointmentTime[3129:c07] This is the StartTime after Selecting BOTH (null)
2013-02-20 21:38:34.069 AppointmentTime[3129:c07] Prepare For Segue StartTime (null)
2013-02-20 21:38:34.069 AppointmentTime[3129:c07] Prepare For Segue EndTime12:15 PM
Q: Why would letsMeet.startTimeLabel show up correct the first time and after selecting EndTime, it changes to NULL. Please note EndTime continues to show the correct Value all the way up to prepareForSegue. Weird!
According to your logs and code , you are entering the switch block twice. Which means you are entering the actionSheet:clickedButtonAtIndex: method twice. So each time you enter the method
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
statement is executed twice, in turn creating two objects. You can see this by doing a fetch from the store.
So you are checking for properties in two different objects and hence the null.
If you are using just one managed object, you can probably add a check for nil for the object before executing insertNewObjectForEntityForName:inManagedObjectContext:. This will make sure you are using the same object.
If you are using more than one object at the same time use the object id or some unique key to identify your object and manipulate it.
Edit:
You can check for nil with the following code:
if(letsMeet==Nil){
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
}
This will work only, if the object you are calling the actionSheet:clickedButtonAtIndex: method is always in memory. But since you are persisting you might want to fetch the object from the store and then check for no. of objects.
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext]];
NSArray *objectArray = [managedObjectContext executeFetchRequest:request error:&error]
if(objectArray.count==0){
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
}else{
letsMeet = (LetsMeet *)[objectArray objectAtIndex:0];
}
Note: If you need to persist only a couple of variables, core-data might be an overkill. Use NSUserDefaults instead and keep it simple.

Failing to add NSDate into NSDictionary

I am trying to addd my nsdate into nsdictionary.CAn anyone tell me how to add it?
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
//if(conditionCount ==0){
if( [#"forecast_information" isEqualToString:elementName] ) {
//conditionDate = get date
NSDate *now=[NSDate date];
isParsingInformation=YES;
NSArray *array=[NSArray arrayWithObject:now];
NSLog(#" the time is %#",array);
[forecastConditions addObject:[NSMutableDictionary dictionary]];
}
else if([#"forecast_date" isEqualToString:elementName])
{
if(!forecast_information)
forecast_information=[[NSMutableArray alloc]init];
}
else if(isParsingInformation){
NSMutableDictionary *field=[forecastConditions lastObject];
[field setObject:[attributeDict objectForKey:#"data"] forKey:elementName];
}
i dnt know..see what I actually want to do is I am getting my google weather api in an nsdictionary named fields..I want to add my NSDate from the system at the first index of nsdictionary..I NSdictionary I couple of data,I want to add my nSdate at the first index..I am not able to do it.
I am trying to increment by date by each loop...how to do it?
i think it is date not data
[field setObject:[attributeDict objectForKey:#"date"] forKey:elementName];
updated code
NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];//creation
[dic setObject:[NSDate date] forKey:#"Today"];//added
NSLog(#"dic is : %# \n\n",dic);
NSDate *now = [NSDate date];
int daysToAdd = 50; // or 60 :-)
NSDate *newDate1 = [now addTimeInterval:60*60*24*daysToAdd];
NSLog(#"Quick: %#", newDate1);
OR
NSDate *now = [NSDate date];
int daysToAdd = 50; // or 60 :-)
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(#"Clean: %#", newDate2);

Core Data complex query

I have model that have field date. I need to fetch all count of records for all day of year or if no record for this day presented fetch as 0. Now i fetch all record for year and make it by hands. Can I do it using core data queries?
Typically in Core Data it is much faster to do all the fetching you will need to do up front rather than breaking it up into multiple fetches.
I tried to count records by day of the year in two ways:
Fetch all the records for a year. Find distinct dates for those records. Loop over the dates and count the records.
Loop over each day in the year. Perform a count-only fetch for the records with that date.
With a small database (48 records), the first approach was about 90 times faster. I imagine the performance of the first approach would get worse as more records are added and the second approach would stay about the same.
Here is the code:
- (void)doFullLoadTestWithYear:(int)year {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Record" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:year];
NSDate *start = [gregorian dateFromComponents:comps];
[comps setDay:31];
[comps setMonth:12];
NSDate *end = [gregorian dateFromComponents:comps];
NSPredicate *yearPred = [NSPredicate predicateWithFormat:#"date >= %# && date <= %#",start,end];
[fetchRequest setPredicate:yearPred];
NSError *error = nil;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
if (error) {
NSLog(#"Error during fetch: %#",[error localizedDescription]);
abort();
}
int dateCount = 0, recordCount = 0;
NSArray *dates = [array valueForKeyPath:#"#distinctUnionOfObjects.date"];
for (NSDate *date in dates) {
NSPredicate *pred = [NSPredicate predicateWithFormat:#"date == %#",date];
NSArray *records = [array filteredArrayUsingPredicate:pred];
dateCount++;
recordCount += [records count];
NSLog(#"%d record(s) with date %#",[records count],date);
}
NSLog(#"Record count for year is %d",recordCount);
NSLog(#"Distinct dates count is %d",dateCount);
}
- (void)doSeparateTestWithYear:(int)year {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Record" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:year];
NSDate *start = [gregorian dateFromComponents:comps];
[comps setYear:year+1];
NSDate *end = [gregorian dateFromComponents:comps];
NSDateComponents *oneDay = [[[NSDateComponents alloc] init] autorelease];
[oneDay setDay:1];
int dateCount = 0, recordCount = 0;
NSDate *date = start;
while (![date isEqual:end]) {
NSPredicate *dayPred = [NSPredicate predicateWithFormat:#"date == %#",date];
[fetchRequest setPredicate:dayPred];
NSError *error = nil;
int count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(#"Error during fetch: %#",[error localizedDescription]);
abort();
}
if (count > 0) {
NSLog(#"%d record(s) with date %#",count,date);
dateCount++;
recordCount += count;
}
date = [gregorian dateByAddingComponents:oneDay toDate:date options:0];
}
NSLog(#"Record count for year is %d",recordCount);
NSLog(#"Distinct dates count is %d",dateCount);
[fetchRequest release];
}

Resources