2011-09-06 84 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