Marks Date on calender Tapku - nsmutablearray

I have below api. I need to mark the days that i have here. But the formate of the library date is like this:
#"2013-08-12 00:00:00 +0000"
How can I add my api below like this date formate?
{
"year": "2013",
"month": "08",
"calendarDays": [ "17", "24" ]
}
I have done something like this, but it didn't worked for me.
//calElem year --> year
//[calElem month] --> month
//self.CalenderDaysArray -->calendarDays
for(int i=0; i<[self.CalenderDaysArray count]; i++){
self.CalenderDaysArray = [NSArray arrayWithObjects:[NSString stringWithFormat:#"%#-%#-%# 00:00:00 +0000",[calElem year],[calElem month],[self.CalenderDaysArray objectAtIndex:i], nil]];
}
Any idea?

I have fixed my problem with below code:
NSMutableArray *datearray=[NSMutableArray array];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [[NSDateComponents alloc] init];
NSArray *myStringArr=[self.CalenderDays objectAtIndex:0];
for(int i=0; i<myStringArr.count; i++){
todayComponents.year = [[calElem year]intValue];
todayComponents.month = [[calElem month] intValue];
todayComponents.day = [[myStringArr objectAtIndex:i]intValue];
todayComponents.hour = 00;
todayComponents.minute = 00;
todayComponents.second= 00;
NSDate *today = [calendar dateFromComponents:todayComponents];
[datearray addObject:[self getdateCalendar:today]];
}

Related

For Loop from Core Data

I have a question, I have 2 arrays (date and descriere), one is keeping a date which I select from a datePicker the other one is an array with strings, Both arrays are fetched from CoreData.
-(void)generateLocalNotification {
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"AddEntrySettings"];
fetchRequest.resultType = NSDictionaryResultType;
NSArray *result = [coreDataStack.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSMutableArray *date = [result valueForKey:#"date"];
NSMutableArray *descriere = [result valueForKey:#"descriere"];`
if (date != nil) {
for (NSString *stringDate in date) {
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:#"MM/dd/yyyy h:mm a"];
[format setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
self.date = [format dateFromString:stringDate];
NSLog(#"LOG:%#",date);
localNotification.fireDate = [self.date dateByAddingTimeInterval:0];
localNotification.timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
for (int i = 0; i < descriere.count; i++) {
localNotification.alertBody = descriere[i];
}
localNotification.applicationIconBadgeNumber = 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.userInfo = #{#"id" : #42};
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];
}
}
}
When I try to fireDate everything is working fine, every time when a date from array is matching with local time I receive a notification till I try to add alertBody, when I make a for loop for alertBody every time is showing just last entry from my NSArray. In CoreData the both entries I adding in the same time. Where is my mistake? How can I make every time to receive a notification with alertBody that matching with date that I insert in CoreData?
The problem is that this for loop:
for (int i = 0; i < descriere.count; i++) {
localNotification.alertBody = descriere[i];
}
will, for every stringDate, iterate to the last item in your descriere array. What you want is to find the index of stringDate in date, and then find the string at the same index in descriere.
But there is an easier way. Don't unpack result into two separate arrays, just access the different values from within the for loop:
if (result != nil) {
for (NSDictionary *dict in result) {
NSString *stringDate = [dict objectForKey:#"date"];
// if necessary, test whether stringDate is nil here
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:#"MM/dd/yyyy h:mm a"];
[format setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
self.date = [format dateFromString:stringDate];
NSLog(#"LOG:%#",date);
localNotification.fireDate = [self.date dateByAddingTimeInterval:0];
localNotification.timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
localNotification.alertBody = [dict objectForKey:#"descriere"];
localNotification.applicationIconBadgeNumber = 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.userInfo = #{#"id" : #42};
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];
}
}

NSFetchedResultsController group into sections for every 4 hours

I'm attempting to group a series of NSManagedObjects into sections. Every section would represent a period of 4 hours within a day.
- (NSString *)sectionIdentifier
{
// Create and cache the section identifier on demand.
[self willAccessValueForKey:#"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:#"sectionIdentifier"];
if (!tmp)
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit) fromDate:[self created]];
tmp = [NSString stringWithFormat:#"%.0f %d %d %d", round(components.hour % 4), components.day, components.month, components.year];
[self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}
In the above code, found in the NSManagedObject, the transient property sectionIdentifier returns a string consisting of the period (of 4 hours) it is in, the day, month, and year of it's creation.
However, although the sort descriptor for the NSFetchedResultController's fetchRequest is set to sort the results in order of their creation date (newest objects at the bottom, oldest at the top), the fetch request is failing due to the section identifier not being ordered properly.
- (NSFetchedResultsController *) fetchedResultsController {
if (!_fetchedResultsController) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"PSSpace" inManagedObjectContext:self.managedObjectContext]];
[fetchRequest setSortDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"created" ascending:YES]]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"sectionIdentifier" cacheName:nil];
[_fetchedResultsController setDelegate:self];
}
return _fetchedResultsController;
}
CoreData: error: (NSFetchedResultsController) The fetched object at index 10 has an out of order section name '1 14 12 2013. Objects must be sorted by section name'
Please can you tell me how I can fix this issue with the ordering?
Thanks.
Try something like
if (!tmp) {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit) fromDate:[self created]];
NSUInteger _y = (components.year * 1000000);
NSUInteger _m = (components.month * 10000);
NSUInteger _d = (components.day * 100);
NSUInteger _h = round(components.hour / 4);
NSUInteger token = (_y + _m + _d + _h);
tmp = [NSString stringWithFormat:#"%lu", token];
[self setPrimitiveSectionIdentifier:tmp];
}

Convert Timestamp to NSDate not working

I have come across a lot of links on stackoverflow and tried to implement code to convert timestamp in this format 2013-07-20T12:23:54.411+05:30 to NSDate of this format
July 20, 2013 (Tuesday) 12:23:54 Or 1 minute ago, 2 days ago format.
I have implemented the following code. The toDate is nil i.e date1 is giving nil value. Seems like Xcode is being sarcastic for this issue
I mean really, what do you think that operation is supposed to mean
with a nil toDate? An exception has been avoided for now. A few of
these errors are going to be reported with this complaint, then
further violations will simply silently do whatever random thing
results from the nil.
Could anyone tell me where i have gone wrong?
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:#"yyyy-mm-ddTHH:mm:ssssZ"];
[dateForm setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
[dateForm setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = [dateForm dateFromString:string];
NSDate *date2 = [NSDate date];
unsigned int unitFlags = NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
// gets the difference between the current date and also the date and time in the timestamp of the data
NSDateComponents *diffComps = [cal components:unitFlags fromDate:date2 toDate:date1 options:0];
int year = ABS([diffComps year]);
int month = ABS([diffComps month]);
int day = ABS([diffComps day]);
int hour = ABS([diffComps hour]);
int minute = ABS([diffComps minute]);
int seconds = ABS([diffComps second]);
NSString *displayTime;
if (year == 0) {
if (month == 0) {
if (day == 0) {
if (hour == 0){
if (minute == 0) {
displayTime = [NSString stringWithFormat:#"about %d secs ago",seconds];
}
else {
displayTime = [NSString stringWithFormat:#"about %d mins ago",minute];
}
}
else {
displayTime = [NSString stringWithFormat:#"about %d hours ago",hour];
}
}
else {
displayTime = [NSString stringWithFormat:#"about %d days ago",day];
}
}
else {
displayTime = [NSString stringWithFormat:#"about %d months ago",month];
}
}
else {
displayTime = [NSString stringWithFormat:#"about %d years ago",year];
}
EDIT: This works fine with a string that i have created in the appdelegate. But not the string I have created in a singleton class.
You are not using the correct time format; I would suggest this:
yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ

For Loop for NSDate

I'm trying to create a for loop with NSDates, so that the loop would increment by 1 day each cycle of the for loop...
NSDate *startDate = datePicker.date;
NSDate *endDate = datePicker2.date;
for (int i = startDate; i < endDate; i++)
{
}
The build fails because of me jamming a NSDate where the int is...
I also tried...
NSDate *startDate = datePicker.date;
NSDate *endDate = datePicker2.date;
for (NSDate *i = startDate; i < endDate; i++)
{
}
That did not build either. Any help would be greatly appreciated, thanks in advance.
for (NSDate *date = [startDate copy]; [date compare: endDate] < 0; date = [date dateByAddingTimeInterval:24 * 60 * 60] )
{
NSLog( #"%# in [%#,%#]", date, startDate, endDate );
}
Using NSDate in While loop

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);

Resources