DateByAddingComponentsとNSDateComponentsによる日付の違いを得る
-
22-09-2019 - |
質問
日付に値を追加し、日付間の違いを得ることに問題があります。計算された日付とコンポーネントは正しくありません。
追加するために、1.5か月を追加すると、1か月しかかかりませんが、整数(1または2または3など)を追加すると、正しく計算されます。
Float32 addAmount = 1.5;
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setMonth:addAmount];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:Date1 options:0];
違いのために、正確に1年(上記とほぼ同じコード)で追加された日付がある場合、正しく追加されますが、差が計算されると、0年、11か月、30日かかります。
NSDate *startDate = Date1;
NSDate *endDate = Date2;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger years = [components year];
NSInteger months = [components month];
NSInteger days = [components day];
私は何が間違っているのですか?また、kcfcalendarcomponentswrap constanctを追加関数と違い関数の両方のオプションに追加しましたが、違いはありません。
ありがとう
解決
So for adding, if I add 1.5 months, I only get 1 month, however if I add any whole number ie (1 or 2 or 3 and etc) it calculates correctly.
The setMonth:
method in NSDateComponents
takes an NSInteger
, not a floating point number. So the behaviour is correct, as it's simply truncating the 1.5 to 1.
Now for difference, if I have a date that has been added with exactly one year (almost same code as above), it adds correctly, but when the difference is calculated, I get 0 years, 11 months and 30 days.
Unless you show the code for how your Date1 and Date2 variables are created, there's no real way to tell.
(You're also leaking memory above; always match an alloc with a release
/autorelease
. And try not to give your variables capital letters, since as a matter of style, that should only be done for class names)
他のヒント
I finally found the problem with the date difference, when I was saving it to a db, I used timeintervalsince1970 with an double value, but when populating it and setting it to a datepicker, I was using a int column type.
Thanks Shaggy Frog for steering me in the right direction.