-1
dateString
の形式は"mm/dd/yyyy '-' HH:mm"
です。 文字列で日付を文字列と時間で抽出したいとします。 私は、次のコードを試してみたが、これは間違った日付を返す:NSDateからの日付と時間の抽出 - 目的C
- (void) extractDate: (NSString *)dateString intoHour: (NSString *)hourLabel and: (NSString*)dateLabel {
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"mm/dd/yyyy '-' HH:mm"];
NSData *date = [formatter dateFromString:dateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date];
hourLabel = [NSString stringWithFormat:@"%lu:%lu", [components hour], [components minute]];
dateLabel = [NSString stringWithFormat:@"%lu/%lu/%lu", [components day], [components month], [components year]];
}
Exemple文字列:"05/01/2015 - 11:15"
結果:日付:1/1/2015
、時間:また、私はこの日付フォーマットを維持することができる方法11:15
をしてdd/mm/yyyy
、日が1
あるとき私が意味する、それがテストされていない01
月の場合は「MM」、それ以外の場合は既にそれを使用しています。 NSNumberFormatterは必要に応じて先行ゼロを使用できます。あるいは、 'NSDateFormatter'を' NSDateComponents'を使う代わりに、あなたが持っている日付から 'NSDateFormatter'を使うこともできます:' [formatter setDateFormat:@ "MM/dd/yyyy"]; dateLabel = [フォーマッタstringFromDate:日付]; [フォーマッタsetDateFormat:@ "HH:mm"]; timeLabel = [formatter stringFromDate:date]; '' timeLabel'/'dateLabel'は' NSString'であり、 'UILabel'ではなく、かなり誤解を招くvar命名です。 – Larme
これを行うにはNSDateFormatterを使うべきです。しかし、あなたの興味のために、 '[NSString stringWithFormat:@"%02d "、[components day]]'を使ってください。 – zcui93
'NSDateFormatter'を使って文字列の各部分を取得する方法 –