2011-06-28 14 views
1

私はこのコードを持っています。私は現在の日時を取得し、日/月/年の部分を保持して時間を変更します。iPhone - 日付と狂気が間違っている

最初に気づくのは、現在の日付と時刻が間違っていることです。正しい時刻の1時間前。それから、私は自分の時間に時間を変更し、それは再び間違っています。

NSDate *today = [NSDate date]; 
// now is june 28, 17:39 pm, printing this to console gives me 
// june 28, 16:39 pm... one hour before... this is the first problem 

// then I change the time... 

// get the current day, month and year 
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 

NSDateComponents *dayX = [gregorian components: NSDayCalendarUnit fromDate: data]; 
NSDateComponents *monthX = [gregorian components: NSMonthCalendarUnit fromDate: data]; 
NSDateComponents *yearX = [gregorian components: NSYearCalendarUnit fromDate: data]; 

NSInteger day = [dayX day]; 
NSInteger month = [monthX month]; 
NSInteger year = [yearX year]; 

// this gives me the correct day, month and year 
// now, create a new date using the current day, month and year but with new hour and minute... 


NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease]; 
[dateComponents setHour:17]; 
[dateComponents setMinute:32]; 
[dateComponents setDay:day]; 
[dateComponents setMonth:month]; 
[dateComponents setYear:year]; 

// the new date is: 16:32????? 
// how can that be if I just set it 17:32?????????? 

任意の手がかり:

これは、コードのですか?

おかげ

+0

を? –

答えて

2

タイムゾーン:

この投稿への回答:あなただけの1 `NSDateComponents`インスタンスを使用していないのはなぜNSDateComponents returning strange hour

[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; 
+0

しかし、私はユーザーのタイムゾーンを知らないとどうすれば解決できますか? – SpaceDog

+0

http://stackoverflow.com/questions/1268509/convert-utc-nsdate-to-local-timezone-objective-c – Steve

+0

あなたの例では、デバイスはどのタイムゾーンに設定されていますか? –

関連する問題