Skip to content

Commit 1260254

Browse files
bzbarsky-applepull[bot]
authored andcommitted
Simplify the NSDate to Matter epoch conversion code. (#29963)
1 parent 1b2231c commit 1260254

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/darwin/Framework/CHIP/MTRConversion.mm

+10-10
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,18 @@ CHIP_ERROR SetToCATValues(NSSet<NSNumber *> * catSet, chip::CATValues & values)
6363

6464
bool DateToMatterEpochSeconds(NSDate * date, uint32_t & matterEpochSeconds)
6565
{
66-
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
67-
NSDateComponents * components = [calendar componentsInTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0] fromDate:date];
66+
auto timeSinceUnixEpoch = date.timeIntervalSince1970;
67+
if (timeSinceUnixEpoch < static_cast<NSTimeInterval>(chip::kChipEpochSecondsSinceUnixEpoch)) {
68+
// This is a pre-Matter-epoch time, and cannot be represented in epoch-s.
69+
return false;
70+
}
6871

69-
if (!chip::CanCastTo<uint16_t>(components.year)) {
72+
auto timeSinceMatterEpoch = timeSinceUnixEpoch - chip::kChipEpochSecondsSinceUnixEpoch;
73+
if (timeSinceMatterEpoch > UINT32_MAX) {
74+
// Too far into the future.
7075
return false;
7176
}
7277

73-
uint16_t year = static_cast<uint16_t>([components year]);
74-
uint8_t month = static_cast<uint8_t>([components month]);
75-
uint8_t day = static_cast<uint8_t>([components day]);
76-
uint8_t hour = static_cast<uint8_t>([components hour]);
77-
uint8_t minute = static_cast<uint8_t>([components minute]);
78-
uint8_t second = static_cast<uint8_t>([components second]);
79-
return chip::CalendarToChipEpochTime(year, month, day, hour, minute, second, matterEpochSeconds);
78+
matterEpochSeconds = static_cast<uint32_t>(timeSinceMatterEpoch);
79+
return true;
8080
}

0 commit comments

Comments
 (0)