How To Search For NSDate? - iphone

I have an NSDate I want to search for in my predicate. However, the timing may not be 2009-12-06 00:00:00 +0000 but may look more like 2009-12-06 3:05:90 +0000. So how can I search for any date that fits within the bounds of that day (24 hours).
Edit:
These are the related methods to the crash:
Crash is happening in this method related to the Calendar's API framework
- (void) reactToTouch:(UITouch*)touch down:(BOOL)down
{
...
if ([marks count] > 0) {
if([[marks objectAtIndex: row * 7 + column] boolValue])
[self.selectedImageView addSubview:self.dot];
else
[self.dot removeFromSuperview];
}else{
[self.dot removeFromSuperview];
}
...
}
This graph sets the graph's date and dots for the date if there is data for that date
- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate {
NSLog(#"calendarMonthView marksFromDate toDate");
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch :[NSArray arrayWithObject:#"timeStamp"]];
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
NSArray *tempData = [objects valueForKey:#"timeStamp"];
NSMutableArray * data1 = [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"]];
[tempData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDate * date = [gregorian dateFromComponents:[gregorian components:flags fromDate:obj]];
[data1 addObject:[formatter stringFromDate:date]];
}];
self.data = data1;
// Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on.
NSMutableArray *marks = [NSMutableArray array];
// Initialise calendar to current type and set the timezone to never have daylight saving
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:startDate];
NSDate *d = [cal dateFromComponents:comp];
// Init offset components to increment days in the loop by one each time
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
// for each date between start date and end date check if they exist in the data array
while (YES) {
// Is the date beyond the last date? If so, exit the loop.
// NSOrderedDescending = the left value is greater than the right
if ([d compare:lastDate] == NSOrderedDescending) {
break;
}
// If the date is in the data array, add it to the marks array, else don't
if ([data containsObject:[d description]]) {
[marks addObject:[NSNumber numberWithBool:YES]];
} else {
[marks addObject:[NSNumber numberWithBool:NO]];
}
// Increment day using offset components (ie, 1 day in this instance)
d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
}
[offsetComponents release];
[request release];
return [NSArray arrayWithArray:marks];
}
And finally, this is the method we came up with, that pushes to the detail view when a date is selected:
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSLog(#"calendarMonthView didSelectDate");
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] )
{
NSDate * searchDate = [formatter dateFromString:dateString];
NSCalendar * calendar1 = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:1];
NSDate * searchDateEnd = [calendar1 dateByAddingComponents:dateComponents toDate:searchDate options:0];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:#"timeStamp >= %# AND timeStamp < %#", searchDate, searchDateEnd];
[request setPredicate: predicate1];
[request setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"xxx array: %#", array);
SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
self.selectedSession = (Session *)[array objectAtIndex:0];
sessionViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
sessionViewController.title = dateString;
sessionViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[dateFormatter release];
[sortDescriptor release];
[request release];
[sortDescriptors release];
}
}
Edit:
When I log the the dates,
The rawDate is straight session.timeStamp and dateString has a date formatter of [dateFormatter setDateFormat:#"eeee, MMM d, y"];
2011-06-27 20:13:44.936 Curl[18714:707] dateString: Monday, Jun 27, 2011
2011-06-27 20:13:44.941 Curl[18714:707] rawString: 2011-06-27 07:05:01 +0000
2011-06-27 20:13:44.961 Curl[18714:707] dateString: Thursday, Jun 23, 2011
2011-06-27 20:13:44.965 Curl[18714:707] rawString: 2011-06-23 08:12:49 +0000
2011-06-27 20:13:44.977 Curl[18714:707] dateString: Wednesday, Jun 22, 2011
2011-06-27 20:13:44.983 Curl[18714:707] rawString: 2011-06-22 21:23:08 +0000
2011-06-27 20:13:44.993 Curl[18714:707] dateString: Tuesday, Jun 21, 2011
2011-06-27 20:13:44.997 Curl[18714:707] rawString: 2011-06-22 03:23:51 +0000
2011-06-27 20:13:45.007 Curl[18714:707] dateString: Monday, Jun 20, 2011
2011-06-27 20:13:45.011 Curl[18714:707] rawString: 2011-06-21 01:03:53 +0000
2011-06-27 20:13:45.020 Curl[18714:707] dateString: Friday, Jun 17, 2011
2011-06-27 20:13:45.024 Curl[18714:707] rawString: 2011-06-18 01:03:53 +0000

Adding a day to searchDate can be done with NSDateComponents using the code below.
NSCalendar * calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:1];
NSDate * searchDateEnd = [calendar dateByAddingComponents:dateComponents
toDate:searchDate
options:0];
Add this after you get the searchDate.
You might also want to change the predicate to
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:#"timeStamp >= %# AND timeStamp < %#", searchDate, searchDateEnd];
Don't check for equality with the upper limit.
Edit
If you look at the code below,
if ([marks count] > 0) {
if([[marks objectAtIndex: row * 7 + column] boolValue])
[self.selectedImageView addSubview:self.dot];
else
[self.dot removeFromSuperview];
}
You don't have checks on the index and since this seems to represent values pertaining to days in a month, I would suggest you check if there is a valid value.
int size = [marks count];
if ((size > 0) && ((row * 7 + column) < size)) {
if([[marks objectAtIndex: row * 7 + column] boolValue])
[self.selectedImageView addSubview:self.dot];
else
[self.dot removeFromSuperview];
}

Related

Incrementing a date's year by one if that date has already passed

I have an array containing birth dates like the one below:
Array(
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
Now I want to make a new array based on whether or not the date has passed. Writing this question in 2013, if a current date has passed then we will change that date's year to 2014. If it hasn't passed then we will have it stay the 2013 date.
For example:
NewArray(
"11/07/2013", no change cus this date hasnt passed yet
"07/10/2013", no change same as above
"20/02/2014" **as date has already passed thats why 2014**
I'm using the following code for this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *curYear = [dateFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
for(int i = 0; i < [_newlymadeArray count]; i++)
{
NSString *dateStr = [_newlymadeArray objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
[dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
[_newlymadeArray replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",_newlymadeArray);
}
NSLog(#"_newlymadeArray%#",_newlymadeArray);
This is however what I get when I NSLog _newlymadeArray:
after replacing (
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
At index 2 it should be "20/02/2014" instead of the 2013 date. What might cause my problem and how can I solve it?
I've made some modifications to your code, and it is working as you want.
In my code I've compared date, which is in Ascending form of current date. If it satisfies the condition, then I've fetched YEAR from matched date, by the DateFormatter "yyyy". Then I simply increment this year by 1, and replace this year in old Date, which is "20/02/2013" to "20/02/2014"
array = [[NSMutableArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
NSDateFormatter *yrFormatter = [[NSDateFormatter alloc] init];
[yrFormatter setDateFormat:#"yyyy"];
NSString *curYear = [yrFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
NSLog(#"%#",curYear);
NSLog(#"%#",nextYear);
dateStr = [dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
NSLog(#"%#",dateStr);
[array replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",array);
}
NSLog(#"_newlymadeArray%#",array);
}
This seems to be working perfectly, so I hope it helps you.
Plese dear try to use this one.I think this one may help
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDate* newDate = [calendar dateByAddingComponents: components toDate:#"YourDate" options: 0];
Otherwise you can use this one code.
if (comResult == NSOrderedSame)
{
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSDate *date = [formatter dateFromString:#"11/07/2013"];
NSDate* newDate = [calendar dateByAddingComponents: components toDate:date options: 0];
// here replace your array object with this "newDate"
}
Compare your array date to today's date with NSDate compare function. Here are the details:
NSString *arrayDateString = #"20/02/2013" // fetch this string from your array
NSDate *todaysDate = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy"];
NSDate* d = [df dateFromString:arrayDateString];
// now compare this date (d) with todaysDate using NSDate function
if ([d compare:todaysdate]== NSOrderedAscending)
{//write your code here}
If it results NSOrderedAscending, then it means array date is earlier than today's date.
So for that date, update year incremented by one using NSDateComponents:
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.year = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Or you can use NSDate function itself:
NSDate *now = arrayDate;
int yearsToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*365*year];
But second option is not full-proof - because of leap year problem.
Hope this two options help you, for solving your issue.
NSArray * array = [[NSArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSMutableArray *output = [NSMutableArray new];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSDate *date = [dateFormatter dateFromString:dateStr];
if ([date compare:now] == NSOrderedAscending)
{
[components setYear:1];
date = [calendar dateByAddingComponents:components toDate:date options:0];
}
dateStr = [dateFormatter stringFromDate:date];
[output addObject:dateStr];
}
NSLog(#"Result : %#",output);

EKCalender creates calendar but can't see it in iCal

I am trying to create a new calendar in iCal. Now I am able to create a new Calendar with some name. But my problem is when I try to create to Local calendar I cant see it in calendar list. Any one have any idea about this? I have tried using all types of sources but not able to find exact solution for this.
Thank you in advance.
NSMutableArray *arrAlarm = [[NSMutableArray alloc]init];
EKAlarm *alarm1 = [EKAlarm alarmWithRelativeOffset:3600];
EKAlarm *alarm2 = [EKAlarm alarmWithRelativeOffset:-3600]; //86400 1 day
[arrAlarm addObject:alarm1];
[arrAlarm addObject:alarm2];
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *ekevent = [EKEvent eventWithEventStore:eventStore];
ekevent.title = strname;
NSLog(#"%#",ekevent.startDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE MMM d,yyyy"];
NSDate *date = [dateFormatter dateFromString:strdate];
// Convert to new Date Format
[dateFormatter setDateFormat:#"YYYY-MM-DD HH:MM:SS ±HHMM"];
NSString *newDate = [dateFormatter stringFromDate:date];
// dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
// [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:#"hh:mm a"];
NSDate* firstDate = [dateFormatter dateFromString:time];
NSDate* secondDate = [dateFormatter dateFromString:endtime];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
// Convert to new Date Format
[dateFormatter setDateFormat:#"HH:MM"];
NSString *t11 = [dateFormatter stringFromDate:firstDate];
NSString *t12 = [dateFormatter stringFromDate:secondDate];
NSDate *dt1 = [dateFormatter dateFromString:t11];
NSDate *dt2 = [dateFormatter dateFromString:t12];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"hh"];
NSString *hourstring = [NSString stringWithFormat:#"%#",
[df stringFromDate:dt1]];
[df setDateFormat:#"mm"];
NSString *minstring = [NSString stringWithFormat:#"%#",
[df stringFromDate:dt1]];
[df release];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: [hourstring intValue]];
[components setMinute: [minstring intValue]];
[components setSecond: 00];
// NSDate *newDate = [gregorian dateFromComponents: components];
[gregorian release];
ekevent.startDate = date;
ekevent.endDate = [[NSDate alloc] initWithTimeInterval:timeDifference sinceDate:date];
[ekevent setCalendar:[eventStore defaultCalendarForNewEvents]];
ekevent.alarms = arrAlarm;
[arrAlarm release];
NSError *err;
[eventStore saveEvent:ekevent span:EKSpanThisEvent error:&err];
Try this code you will get the desired result.

Format date on iPhone returns (null)

I have a date with the format:
Fri Jul 16 16:58:46 +0000 2010.
To convert it to Fri Jul 16 2010 I tried:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
for(int i=0; i<[self.data count]; i++) {
id celldata = [self.data objectAtIndex:i];
NSString *str = [NSString stringWithFormat:#"%#", [celldata objectForKey:#"created_at"]];
NSLog(#"date for %u is %#",i, str); //this works and writes the date
[df setDateFormat:#"eee MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [df dateFromString:str];
[df setDateFormat:#"eee MMM dd yyyy"];
NSString *dateStr = [df stringFromDate:date];
NSLog(#"%#",dateStr);
}
But NSLog(#"%#",dateStr) only writes (null). How to get it working?
EDIT
For whatever reason I got it working by changing
[df setDateFormat:#"eee MMM dd HH:mm:ss Z yyyy"];
to
[df setDateFormat:#"MMM dd HH:mm:ss Z yyyy"];
and deleting the week day from my string. However, thank you all.
This might help you out a bit. I had a similar problem a while back, so I created the following methods.
Definitions
#define DATE_TYPE_hhmmss [NSArray arrayWithObjects:#"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYY [NSArray arrayWithObjects:#"M", #"D", #"Y", nil]
#define DATE_TYPE_MMDDYYYYhhmmss [NSArray arrayWithObjects:#"M", #"D", #"Y", #"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYYWWhhmmss [NSArray arrayWithObjects:#"M", #"D", #"Y", #"W", #"h", #"m", #"s", nil]
#define DATE_TYPE_MMDDYYYYhhmmssWW [NSArray arrayWithObjects:#"M", #"D", #"Y", #"h", #"m", #"s", #"W", nil]
#define DATE_TYPE_YYYYMMDD [NSArray arrayWithObjects:#"Y", #"M", #"D", nil]
#define DATE_TYPE_YYYYMMDDhhmmss [NSArray arrayWithObjects:#"Y", #"M", #"D", #"h", #"m", #"s", nil]
#define DATE_TYPE_YYYYMMDDWWhhmmss [NSArray arrayWithObjects:#"Y", #"M", #"D", #"W", #"h", #"m", #"s", nil]
#define DATE_TYPE_YYYYMMDDhhmmssWW [NSArray arrayWithObjects:#"Y", #"M", #"D", #"h", #"m", #"s", #"W", nil]
#define DATE_TYPE_FRIENDLY [NSArray arrayWithObjects:#"xx", nil]
Date Methods
Create Date From Values
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
[dateFormatter setDateFormat:#"HH"];
[dateComponents setHour:hour];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMinute:minute];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
-(NSDate *) getDateWithMonth:(int)month day:(int)day year:(int)year hour:(int)hour minute:(int)minute second:(int)second {
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMonth:month];
[dateFormatter setDateFormat:#"DD"];
[dateComponents setDay:day];
[dateFormatter setDateFormat:#"YYYY"];
[dateComponents setYear:year];
[dateFormatter setDateFormat:#"HH"];
[dateComponents setHour:hour];
[dateFormatter setDateFormat:#"MM"];
[dateComponents setMinute:minute];
[dateFormatter setDateFormat:#"SS"];
[dateComponents setSecond:second];
NSDate * result = [calendar dateFromComponents:dateComponents];
return result;
}
Get String From Date
-(NSString *) getStringFromDate:(NSDate *)date dateType:(NSArray *)dateType {
NSString * result = #"";
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSString * format = #"";
NSDateComponents * dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger weekday = [dateComponents weekday];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
if (dateType != nil) {
for (int x = 0; x < [dateType count]; x++) {
if (x == ([dateType count]-1)) {
if ([[dateType objectAtIndex:x] isEqualToString:#"Y"]) {
format = [format stringByAppendingFormat:#"%d", year];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"M"]) {
format = [format stringByAppendingFormat:#"%d", month];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"D"]) {
format = [format stringByAppendingFormat:#"%d", day];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"W"]) {
format = [format stringByAppendingFormat:#"%d", weekday];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"h"]) {
format = [format stringByAppendingFormat:#"%d", hour];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"m"]) {
format = [format stringByAppendingFormat:#"%d", minute];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"s"]) {
format = [format stringByAppendingFormat:#"%d", second];
}
} else {
if ([[dateType objectAtIndex:x] isEqualToString:#"Y"]) {
format = [format stringByAppendingFormat:#"%d|", year];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"M"]) {
format = [format stringByAppendingFormat:#"%d|", month];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"D"]) {
format = [format stringByAppendingFormat:#"%d|", day];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"W"]) {
format = [format stringByAppendingFormat:#"%d|", weekday];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"h"]) {
format = [format stringByAppendingFormat:#"%d|", hour];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"m"]) {
format = [format stringByAppendingFormat:#"%d|", minute];
} else if ([[dateType objectAtIndex:x] isEqualToString:#"s"]) {
format = [format stringByAppendingFormat:#"%d|", second];
}
}
if ([[dateType objectAtIndex:x] isEqualToString:#"xx"]) {
format = [NSString stringWithFormat:#"Year: %d, Month: %d, Day: %d, Weekday: %d, Hour: %d, Minute: %d, Second: %d", year, month, day, weekday, hour, minute, second];
}
}
} else {
format = [format stringByAppendingFormat:#"%d|", year];
format = [format stringByAppendingFormat:#"%d|", month];
format = [format stringByAppendingFormat:#"%d|", day];
format = [format stringByAppendingFormat:#"%d|", weekday];
format = [format stringByAppendingFormat:#"%d|", hour];
format = [format stringByAppendingFormat:#"%d|", minute];
format = [format stringByAppendingFormat:#"%d|", second];
format = [NSString stringWithFormat:#"%d|%d|%d|%d|%d|%d|%d", year, month, day, weekday, hour, minute, second];
}
result = format;
return result;
}
Example
NSDate * date = [self getDateWithMonth:12 day:24 year:1994];
NSString * dateInString = [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY];
int month = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:0] intValue];
int day = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:1] intValue];
int year = [[[dateInString componentsSeparatedByString:#"|"] objectAtIndex:2] intValue];
NSLog(#"String of Date: \"%#\"", dateInString);
NSLog(#"Month: %d", month);
NSLog(#"Day: %d", day);
NSLog(#"Year: %d", year);
The method [self getDateWithMonth:12 day:24 year:1994] returns an NSDate object which is usually hard to read, so you can use [self getStringFromDate:date dateType:DATE_TYPE_MMDDYYYY] to get a string of an NSDate object.
Use the definitions (macros) to specify the format of the date you would like to get in the string.
For example:
DATE_TYPE_hhmmss would return the Hour|Minute|Second,
DATE_TYPE_MMDDYYYY would return the Month|Day|Year,
DATE_TYPE_MMDDYYYYhhmmss would return the Month|Day|Year|Hour|Minute|Second,
DATE_TYPE_MMDDYYYYWWhhmmss would return the Month|Day|Year|Weekday (#)|Hour|Minute|Second
and so on...
Console Log
2012-04-29 13:42:15.791 Atomic Class[1373:f803] String of Date: "12|24|1994"
2012-04-29 13:42:15.793 Atomic Class[1373:f803] Month: 12
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Day: 24
2012-04-29 13:42:15.794 Atomic Class[1373:f803] Year: 1994
If the original strings you are parsing to dates are really in the format of "20081122" then the first call to "setDateFormat" is incorrect in both snippets, as the format of the specified is incorrect.
Assuming that [celldata objectForKey:#"created_at"] is returning dates in the format of "20081122" per your second code snippet, you need to change the first call to setDateFormat to use the correct format for the string, "yyyyMMdd" This will drive a correct conversion when you call the method "dateFromString" Then, once you have a NSDate* object representation, you can use whatever format you need when you convert it back to a string via stringFromDate.
NSString *dateStr = #"20081122";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//This is the important change here, this format MUST match the format of the string.
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
Use Dateformatter for week EEE instead of eee
[df setDateFormat:#"EEE MMM dd HH:mm:ss Z yyyy"];
I hope this will be helpful to you...

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.

Getting Error with pushing view on NavBar

When I push a view, I am getting the following errors in the console:
nested push animation can result in corrupted navigation bar
Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
Any ideas how to fix this?
This is the method that pushes the new veiw:
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
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] )
{
NSDate * searchDate = [formatter dateFromString:dateString];
NSCalendar * calendar1 = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:1];
NSDate * searchDateEnd = [calendar1 dateByAddingComponents:dateComponents toDate:searchDate options:0];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:#"timeStamp >= %# AND timeStamp < %#", searchDate, searchDateEnd];
[request setPredicate: predicate1];
[request setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"xxx array: %#", array);
SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
self.selectedSession = (Session *)[array objectAtIndex:0];
sessionViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
sessionViewController.title = dateString;
sessionViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[dateFormatter release];
[sortDescriptor release];
[request release];
[sortDescriptors release];
}
}