質問
DatePickerを使用して日付を選択したという点でアプリケーションを開発していますが、時間とともに日付を与えてくれます。その形式を文字列に変換しました。どうすればいいですか。plzは私に何かを提案します。
以下は私のコードスニペットです。
NSDate *selected =[datePicker date];
NSString *dateString = [NSString stringWithFormat:@"%@", selected];
ここで、ピッカーはuidatepickerのオブジェクトです。
解決
使用できます NSCalendar
あなたの日付の月、日、年のコンポーネントを取得するために、それらを操作し、それらを再組み立てします。これがコードの例です。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];
[otherDateComponents setYear:[dateComponents year]];
[otherDateComponents setMonth:[dateComponents month]];
[otherDateComponents setDay:[dateComponents day]];
NSDate *newDate = [calendar dateFromComponents:otherDateComponents];
現在のカレンダーはロケール固有であるため、戻ってきた値はすべてのデバイスで同じではないことに注意してください。あなたの目的のために特定のカレンダーを指定することをお勧めします。 NSGregorianCalendar
西部で最も頻繁に使用されるものです。
他のヒント
これが別の解決策です:
NSDate *selected =[datePicker date];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *day = [formatter dateFromString:[formatter stringFromDate:selected]];
[formatter release];
所属していません StackOverflow