2011-09-06 79 views
1

我想将一个nsstring转换为nsdate .i创建了一个全局变量,其中我保存从datepicker中选取的日期,然后将此变量转换为nsdate为datefromstring函数。但字符串没有被转换成日期。可能是什么问题。如何将nsstring转换为iphone中的nsdate

TTimePickercontroller: 
This is the class in which i have the code for the picker 

-(NSString *)convertDueDateFormat{ 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setLocale:[NSLocale currentLocale]]; 
    [dateFormatter setFormatterBehavior: NSDateFormatterBehavior10_4]; 
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
    dateString = [dateFormatter stringFromDate:datePicker.date]; 

    return dateString; 
//dateString is an nsstring variable that has been declared globally. 
} 

TAddAlarmController. 
this is another class in which i want to convert the dateString varibale into nssdate 
-(IBAction)save{ 

    timepicker = [[TTimePickerController alloc]init]; 
    NSDateFormatter* df = [[NSDateFormatter alloc] init]; 
    [df setDateFormat:@"hh:mm"]; 
    d = [df dateFromString:dateString]; 
    NSLog(@"%@", d); 
    //Here i am using the dateFromString function and converting the string variable dateString into nsdate variable d .in dateString variable value is getting passed but in d the value is not getting passed. 


} 
Please help me in solving the problem.Thanks 
+0

的可能重复的[转换的NSString的NSDate](http://stackoverflow.com/questions/1809379/convert-nsstring-to-nsdate) –

回答

0
Try this code this will help you because I run this code successfully and return time. 

UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)]; 
pickerView.datePickerMode = UIDatePickerModeDate; 
pickerView.hidden = NO; 
pickerView.date = [NSDate date]; 
[self.view addSubview:pickerView]; 
NSString *dateString; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh:mm"]; 
dateString = [dateFormatter stringFromDate:pickerView.date]; 
NSLog(@"String into Date:--->%@",dateString); 
+0

nikunj但但是当我将此dateStrimg转换为nsdate它没有得到正确转换。 – Rocky

+0

如果我选择1.00 pm它显示7.30 pm在我的nsdate变量 – Rocky

+0

nikunj你在那里 – Rocky

2
-(NSString *)convertDueDateFormat{ 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh:mm"]; 
dateString = [dateFormatter stringFromDate:datePicker.date]; 
    ////some code  

}

Try like this, 
+0

,但是当我将它转换为D在控制台它显示:1970-01-01 05:24:00 +0000 – Rocky

+0

我只想要时间05:24 – Rocky