1

NSDate文字列からオブジェクトを取得しようとしています。休閑コードを使用します

NSString *st1=@"4:39 AM";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSDate *dateobj=[dateFormatter dateFromString:st1];
NSLog(@"Date from string 4:39 AM is %@",dateobj);

しかし、それは次のような間違った出力を与えます

文字列4:39AMからの日付は1969-12-3123:09:00+0000です

NSDateこのタイプの文字列からオブジェクトを取得する正確な方法は何ですか。

4

2 に答える 2

4

NSLogingに基づいて結果を作成しないでください。NSDateログに記録すると、GMTで時間が表示されます。この質問に対する私の回答を参照してください。NSDateFormatterは、4時間先の時間を表示します。

たとえば、UILocalNotification午前4時39分に発砲したい場合は、次のようにします。

NSCalendar* myCalendar = [NSCalendar currentCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit 
                                             fromDate:[NSDate date]];
//4:39 Am
[components setHour: 4]; //4 am
[components setMinute: 39];//39 minutes
[components setSecond: 0];// 0 seconds
NSDate *myDate = [myCalendar dateFromComponents:components];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd, yyyy h:mma"];  
NSString *str = [formatter stringFromDate:myDate];

NSLog(@"date is %@", myDate); //This will log the correct data but in GMT time zone
NSLog(@"date is %@", str); //This will log the correct data

UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = myDate;
于 2012-06-11T09:09:22.663 に答える
2

正解です。日付ではなく時間のみを指定しました。このように、日付はコンピューター時代の始まり1970/1/1(コンピューターのゼロ時間)であると想定されます。NSLog次に、タイムゾーン(GMT-5)に応じて表示します。

より良い答えが必要な場合は、必要な出力を指定する必要があります。コードは正しく、結果も正しいです。

于 2012-06-11T09:15:42.050 に答える