如何将事件添加到默认日历

时间:2011-11-16 06:10:21

标签: iphone objective-c events calendar nsdateformatter

大家好我需要保存事件存储在默认日历中。所以我需要将给定的日期字符串转换为Nsdate.Here我没有得到正确的格式..可以任何帮助....我给我的代码如下......

我的日期字符串是// startdate - 格式--- November 19 2011 9:30 PM这种格式..我写的是这样的

NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init]; 
[dateformatter setDateFormat:@"MMMM dd yyyy H:m a"]; 

NSLog(@"start date is %@",startdate); 
NSDate *dates=[[NSDate alloc]init]; 
dates=[dateformatter dateFromString:startdate]; 

NSLog(@"date is %@",dates); 

我得到这样的输出我需要为event.i我没有得到确切的时间...日期是2011-11-19 07:00:00 +0000

2 个答案:

答案 0 :(得分:2)

试试这个(对我来说很好):

NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init]; 
[dateformatter setDateFormat:@"MMMM dd yyyy h:m a"]; 

NSLog(@"start date is %@",startdate); 
NSDate *dates = [dateformatter dateFromString:startdate]; 

NSLog(@"date is %@",dates);

如果您想设置特定时区,请使用方法setTimeZone

[dateformatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Moscow"]];

答案 1 :(得分:0)

最后我找到了错误的解决方案。该代码在下面

- (IBAction为)notifyButtonpressed:(ID)发送方 {     NSLog(@“按下通知按钮”);

EKEventStore *eventStore = [[EKEventStore alloc] init];

EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
event.title=location;


//startdate--format---November 19 2011 9:30 PM

NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init]; 

NSDate *date=[NSDate date];
[dateformatter setDateFormat:@"Z"];

NSString *timezones=[dateformatter stringFromDate:date];

NSLog(@"time zone is %@",timezones);
NSMutableString *new_start=[[NSMutableString alloc]init];



[new_start appendString:[NSString stringWithFormat:@"%@ %@",startdate,timezones]];

NSLog(@"after0000-----append is %@",new_start);


[dateformatter setDateFormat:@"MMMM dd yyyy hh:mm a Z"]; 

NSLog(@"start date is %@",startdate);
NSDate *startdates = [dateformatter dateFromString:new_start]; 

NSMutableString *new_start1=[[NSMutableString alloc]init];


[new_start1 appendString:[NSString stringWithFormat:@"%@ %@",enddate,timezones]];


NSDate *enddates=[dateformatter dateFromString:new_start1]; 
NSLog(@"-------date is %@ ,%@------",startdates,new_start1);


event.title=Title;



NSLog(@"start date is %@--",startdates);
event.startDate =[startdates initWithTimeInterval:600 sinceDate:startdates];

event.endDate=enddates; 





[event setCalendar:[eventStore defaultCalendarForNewEvents]];

NSLog(@"event start date is %@ and enddate is %@",event.startDate,event.endDate);
NSError *err;

[eventStore saveEvent:event span:EKSpanThisEvent error:&err]; 

if(!err)
{

    UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:Title message:@"Event Added successfully " delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

    [alertview show];
    [alertview release];

}


NSLog(@"error is %@",err);

}