Color not changing of Calendar Item - ios

I am using CKCalendar for making calendar . I want to change color of date which is in my Array. I am using present Array
present =[[NSMutableArray alloc]init];
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
[present addObject:newDate1];
The value present Array is showing "2015-09-03 07:37:30 +0000"
When i am apply the method for change the color.
- (void)calendar:(CKCalendarView *)calendar configureDateItem:(CKDateItem *)dateItem forDate:(NSDate *)date {
// TODO: play with the coloring if we want to...
NSLog(#"%#",date); // 2015-09-03 18:30:00 +0000
NSLog(#"%#",present); //"2015-09-03 07:37:30 +0000"
if ([present containsObject:date]) {
dateItem.backgroundColor = [UIColor redColor];
}
}
They show diffrent value so they not enter in my Code . Please Help . I am stuck .Any help would be apperciated.

Related

How to set the maximum date in MDDatePicker in objective c

I am Setting Maximum date but not able to disable Remaining date
Example like - Date of Birth Selection.
Any one has idea about that.
thanks in Advance.
-(void) dateTextField:(id)sender
{
UIDatePicker *picker = (UIDatePicker*) dateOfBirthField.inputView;
// [picker setMaximumDate:[NSDate date]];
[picker setMinimumDate:[NSDate date]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDate *eventDate = picker.date;
[dateFormat setDateFormat:#"yyyy/MM/dd"];
NSString *dateString = [dateFormat stringFromDate:eventDate];
dateOfBirthField.text = [NSString stringWithFormat:#"%#",dateString];
}
MDDatePickerDialog class uses MDCalendar to manage its minimum date. If you will look at the implementation of MDCalendar you will find following implementation in initialize method:
_maximumDate = [NSDateHelper mdDateWithYear:2037 month:12 day:31];
First try setting this date to a static value of your choice to see this is the required variable, then you can move this property declaration to header file of MDCalendar to make this maximumDate variable accessible outside the class. As a next step you can make a property in MDDatePickerDialog to set maximum date in the same way it sets minimum date.
A part from MDDatePicker.m file
- (void)setMinimumDate:(NSDate *)minimumDate {
self.calendar.minimumDate = minimumDate;
}
P.S. Remember to handle the date validations like date should be valid and maximum date should not be earlier than minimum date etc.
Hope that helps!
You just have to add date whatever you want to make maximum, here I have to make only a week date should be selected from the current date, So here is the code which I've written, where you show the date picker just add one line:
- _datePicker.maximumDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*7]; ;
After that search this method into MDCalender.m file and replace with this code.
- (BOOL)shouldSelectDate:(NSDate *)date {
BOOL result;
if ([self.maximumDate timeIntervalSince1970] >= date.timeIntervalSince1970 ) {
result =
(date.timeIntervalSince1970 >= self.minimumDate.timeIntervalSince1970);
return result;
}
return result;
}
It worked for me. Thanks

Formatting a month string is not working

I'm trying to create month strings that look like "Jan", "Feb", "Mar"... Here is my code:
- (NSString *)getMonthNameString:(int)monthNumber {
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"MMM"];
NSArray *monthNames = [formatter standaloneMonthSymbols];
NSString *monthName;
if (monthNumber > 0) {
return monthNames[monthNumber - 1];
}
return monthNames[1];
}
So if the month number is 1, I'm expecting the code to provide month name as "Jan" and if it is 2, it has to provide month name as "Feb" and so on. But the problem is that even though I have set the format as MMM, it is still creating month names of type "January", "February" etc instead of "Jan","Feb" etc. How do I sort this out?
Try:
-(NSString*)getMonthNameString:(int)monthNumber
{
NSDateFormatter *formate = [NSDateFormatter new];
[formate setDateFormat:#"MMM"];
NSArray *monthNames = [formate shortMonthSymbols];
NSString *monthName;
if (monthNumber > 0)
{
monthName = [monthNames objectAtIndex:(monthNumber - 1)];
}
return monthName;
}
That's usually not what a NSDateFormatter is for - it is for converting real dates, and not just month numbers.
If you want to stick with it, I suggest
-(NSString*)getMonthNameString:(int)monthNumber {
NSDateFormatter *formatter = [NSDateFormatter new];
return formatter.shortMonthSymbols[monthNumber-1];
}
I see no benefit in the extra check for > 0. This just masks programming errors. You might want to add an assertion to catch that during development. (Why should an invalid number return January anyway?)
Creating formatters is expensive, though - you might want to reuse the same instance over and over again.
Or just access an array directly, i.e.
-(NSString*)getMonthNameString:(int)monthNumber {
return #[#"Jan", #"Feb", ...][monthNumber-1]; // write up to December of course
}
standaloneMonthSymbols is a property of NSDateFormatter. I don't think it uses the dateFormat you've set. Try using shortStandaloneMonthSymbols property instead (or veryShortStandaloneMonthSymbols if you just need one letter symbol).
tahavath is right. Specifically, you want to use the shortStandaloneMonthSymbols property to get it to print "Jan" or "Feb" etc.
Try the following:
-(NSString*)getMonthNameString:(int)monthNumber
{
NSDateFormatter *formate = [NSDateFormatter new];
[formate setDateStyle:NSDateFormatterMediumStyle];
[formate setDateFormat:#"MMM"];
NSArray *monthNames = [formate standaloneMonthSymbols];
NSString *monthName;
if (monthNumber > 0)
{
monthName = [monthNames objectAtIndex:(monthNumber - 1)];
}
return monthName;
}
Check your code #Karuppu MGR
-(NSString*)getMonthNameString:(int)monthNumber
{
NSDateFormatter *formate = [NSDateFormatter new];
[formate setDateFormat:#"MMM"];
NSArray *monthNames = [formate standaloneMonthSymbols];
NSString *monthName;
if (monthNumber > 0 && monthNumber<13)
{
monthName = [monthNames objectAtIndex:(monthNumber - 1)];
// your process is right but , here you have attached "return value " so every time return the monthNames array value.
}
return monthName; // if you pass zero or greathan twelve monthName return nil value
}

error in using date picker

the application crashed when calling this function, how ever in iPhone it works fine , but in iPad the application crashes and say
note: i'm using ActionSheetDatePicker library
Thread 1: EXC_BAD_ACCESS (cod = 1 , address = 0x9e...)
when i debug i found selectedDate is nil in iPad , but works fine in iPhone
#pragma mark - Implementation
- (void)dateWasSelected:(NSDate *)selectedDate element:(id)element {
// self.selectedDate = selectedDate;
//may have originated from textField or barButtonItem, use an IBOutlet instead of element
//DATE TEXT FIELD HERE
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:selectedDate];
self.textFieldBirthDate.text = stringFromDate ;
birthDate = stringFromDate ;
//"YYYY-MM-DD" the birthdate format
}
The git hub code which you provided is working fine for me and I did debug the code.
When user Taps on done button (After selecting the date) below code will be executed.
- (void)notifyTarget:(id)target didSucceedWithAction:(SEL)action origin:(id)origin {
if ([target respondsToSelector:action])
objc_msgSend(target, action, self.selectedDate, origin);
else
NSAssert(NO, #"Invalid target/action ( %s / %s ) combination used for ActionSheetPicker", object_getClassName(target), (char *)action);
}
Now here make sure you are getting value for self.selectedDate , if you are not getting then please do check that you are getting a breakpoint to below code when you just select a date by scrolling.
- (void)eventForDatePicker:(id)sender {
if (!sender || ![sender isKindOfClass:[UIDatePicker class]])
return;
UIDatePicker *datePicker = (UIDatePicker *)sender;
self.selectedDate = datePicker.date;
}
These codes are present in file
ActionSheetDatePicker.m
If you are getting the breakpoint here then make sure you are saving the date .Once you do check this the problem will be resolved.
Regards,
Anil

Load an image on specific date and time in iOS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My question is: how do I load a specific image on a specific date and time in iOS?
I have searched the net but did not find anything useful.
I have a list of images in an imageArray and want every image to be shown on a specific date, time and order.
Fx. say I want to load MyImage on MyDateAndTime. How can I do this?
Image 1 - DateAndTime 1
Image 2 - DateAndTime 2
Image 3 - DateAndTime 3
Any suggestions is appreciated, please provide some source code if possible.
I put simple logic, edit it as per your requirement otherwise if you have any query related to my answer then please tells to me.
Best way is store your image with Name of dateTime (dd_MM_yyyy_HH_mm_ss) and access image name such like,
NSString *imageName
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd_MM_yyyy_HH_mm_ss"];
imageName = [NSString stringWithFormat:#"%#.png", [formatter stringFromDate:[NSDate date]]]; // here you can set specific dateTime, i putted current dateTime
Here you get imageName such like 19_10_2013_6_13_21.png
And by this image name you can get image from bundle or document directory.
If all you want is to show a different image every minute, use this, otherwise skip below to see helpful date information.
NSTimeInterval secondsInMinute = 60;
[NSTimer timerWithTimeInterval:secondsInMinute target:self selector:#selector(minuteChanged:) userInfo:nil repeats:YES];
- (void)minuteChanged:(id)sender {
// change image here
}
You question could have many different answers, do you want to create this date dynamically? or is it a a predefined date? One solution is to get get the timeInterval of the date you are looking for.
NSDate* rightNow = [NSDate date];
NSTimeInterval timeInterval = [rightNow timeIntervalSince1970];
// since time intervals are in seconds we can just append the
// date as easily as adding time
NSInteger secondsInMinute = 60;
NSInteger minutesInHour = 60;
NSInteger hoursInDay = 24;
NSInteger daysInWeek = 7;
NSInteger secondsInWeek = secondsInMinute * minutesInHour * hoursInDay * daysInWeek;
timeInterval = timeInterval + secondsInWeek;
NSDate* aWeekInFuture = [NSDate dateWithTimeIntervalSince1970:timeInterval];
that i would say is the easiest to under stand to set a date, but you could also use components to set a future date dynamically. This leads into some problems but here is how it's done.
NSDate* rightNow = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* dateCompenents = [calendar components:(NSDayCalendarUnit | NSWeekCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:rightNow];
[dateCompenents setDay:dateCompenents.day + 7];
NSDate* aWeekInFuture = [calendar dateFromComponents:dateCompenents];
to help explain this, here is some console logs
(lldb) po rightNow
$0 = 0x0b933440 2013-10-19 12:43:55 +0000
(lldb) po aWeekInFuture
$1 = 0x0ba32a60 2013-10-26 04:00:00 +0000
you see how the date is accurate for the day, year, month, but look at the exact time, the current time (right now) is 12:43:55 but the week in he future is 4:00:00 this is because i did not ask for the NSMinutesCalendarUnit, NSHoursCalendarUnit, NSSecondsCalendarUnit... so if i wanted a perfect date that would be inadequate unless i ask for every single thing, but you specifically may not need to be so accurate in fact you may even want to set your own time.
Now if you want a static date, a date the user enters, you will need to use NSDateFormatter example below
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:currentCalendar];
[dateFormatter setDateFormat:#"mm/dd/yyyy"];
NSDate* birthdayDate = [dateFormatter dateFromString:#"10/05/2013"];
Now you wanted to know how would you know if today is the specified date that is saved. Lets say you stored the date in NSUserDefaults or on a server or some place, the easiest way to compare the dates is with the compare function of an NSDate
NSDate* rightNow = [NSDate date];
NSDate* storedDate = [[NSUserDefaults standardUserDefaults] objectForKey#"storedDate"] // some date from server, or UserDefaults
NSComparisonResult = [rightNow compare:storedDate];
this is a bit inadequate since it test for perfection but it will return values of NSOrderedSame if they are equal, NSOrderedDescending if storedDate is behind rightNow, and NSOrderedAscending if storedDate is in front of rightNow. This is all specific down to the time interval. If you just want a generic day, you will have to test it via components
NSDate* rightNow = [NSDate date];
NSDate* birthdayDate = [[NSUserDefaults standardUserDefaults] objectForKey#"birthday"]
NSDateComponents* todayComponents = [currentCalendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:rightNow];
NSDateComponents* birthdayComponents = [currentCalendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:birthdayDate];
BOOL dayIsTheSame = ( todayComponents.day == birthdayComponents.day );
BOOL monthIsTheSame = ( todayComponents.month == birthdayComponents.month );
BOOL todayIsBirthday = ( dayIsTheSame && monthIsTheSame );
if (todayIsBirthday) {
[self.imgViewBirthday setImage[UIImage imageNamed:#"cake.png"]];
}
In your question you specified an array of images, lets say you have a different image depending on which hour it is, or which minute, you would use the component, todayComponent.minute after asking for the NSMinutesCalendarUnit as the index of this array;
UIImage* currentImageToDisplay = [self.arrayOfImage objectAtIndex:todayComponent.minute];
self.imageView.image = currentImageToDisplay;
References:
NSDate,
NSDateFormatter,
NSDateComponents,
NSCalendar,
NSTimer
If I understood your problem now, one fancy approach using a recursive block you might check out is this:
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSArray* dates = #[#1, #1, #1, #1, #1, #1, #1, #1, #1];
NSArray* urls = #[#"A", #"B", #"C", #"D", #"E", #"F", #"G", #"H", #"I"];
NSEnumerator* dateIter = [dates objectEnumerator];
NSEnumerator* urlIter = [urls objectEnumerator];
typedef void(^block_t)(NSEnumerator* dateIter, NSEnumerator* urlIter);
block_t asyncFunc;
__block __weak block_t _asyncFunc = asyncFunc = ^(NSEnumerator* dateIter, NSEnumerator* urlIter) {
NSNumber* date = [dateIter nextObject];
NSString* url = [urlIter nextObject];
if (date != nil && url != nil) {
double delayInSeconds = [date doubleValue];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_global_queue(0, 0), ^(void){
NSLog(#"%#", url);
_asyncFunc(dateIter, urlIter);
});
}
else {
printf("\n");
return;
}
};
// start:
asyncFunc(dateIter, urlIter);
sleep (10);
}
return 0;
}
Note:
The "dates" are actually "delays" and the URLs are actually just strings in this example. You should be able to adjust this as you like. Of course, NSLog(#"%#", url); would actually display your image.
Also, the block asyncFunc is asynchronous!

creating formatted NSDate using NSDateFormatter or mktime

I'm just trying to create a NSDate object with string as:2011-02-10 4:30:45
Take a look at the code:
Approach OBJC:
-(NSDate *)get_date_df:(NSString *)dstr
{
NSLog(#"1> %#",dstr);
NSDateFormatter *df_in = [[[NSDateFormatter alloc] init]autorelease];
[df_in setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *d = [df_in dateFromString:dstr];
NSLog(#"2> %#",d);
NSLog(#"3> %#",[df_in stringFromDate:d]);
return d;
}
And here's the output:
1> 2011-02-10 4:30:45
2> 2011-02-09 23:00:45 +0000
3> 2011-02-10 04:30:45
So why is 2> getting printed wrong?
Suppose at 2011-02-10 4:20:45, I try setting up a LocalNotification with that date, it fires instantly because the processor assumes the time is already expired!
UILocalNotification *lnf = [[UILocalNotification alloc] init];
[lnf setFireDate:[self get_date_df:#"2011-02-10 4:30:45"]];
[lnf setAlertBody:#"WTF"];
[[UIApplication sharedApplication]scheduleLocalNotification:lnf];
[lnf release];
And, I've already tried setting up various TimeZones and NSLocale for en_US, en_FR. No help.
Approach C:
And FYI now I'm switching to C, trying something with:
-(NSDate *)get_date_c:(const char *)date_str
{
char date[10][6] = {0};
sscanf(date_str,"%[0-9] - %[0-9] - %[0-9] %[0-9] : %[0-9] : %[0-9]",date[0],date[1],date[2],date[3],date[4],date[5]);
struct tm *t_info = (struct tm *)malloc(sizeof(struct tm));
t_info->tm_sec = atoi(date[5]);
t_info->tm_min = atoi(date[4]);
t_info->tm_hour = atoi(date[3]);
t_info->tm_mday = atoi(date[2]);
t_info->tm_mon = atoi(date[1]);
t_info->tm_year = atoi(date[0]);
NSLog(#"ans: %f",(double)mktime(t_info));
NSDate *d = [NSDate dateWithTimeIntervalSince1970:mktime(t_info)];
free(t_info);
return d;
}
Output:
ans: -1.000000
There again I'm stuck with converting time_t to NSTimeInterval.
So, thanks in advance if you could help me out with any approach :(
In your input string and format yyyy-MM-dd HH:mm:ss you didn't specify the timezone. So it defaults to UTC.

Resources