Date.h (2280B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef DOM_QUOTA_DATE_H_ 8 #define DOM_QUOTA_DATE_H_ 9 10 #include "mozilla/CheckedInt.h" 11 #include "mozilla/dom/quota/Constants.h" 12 #include "prtime.h" 13 14 namespace mozilla::dom::quota { 15 16 /** 17 * A lightweight utility class representing a date as the number of days since 18 * the Unix epoch (1970-01-01 UTC). 19 * 20 * This class is useful when full timestamp precision is not needed and only 21 * a compact representation is required, such as when storing the value in an 22 * int32_t field. An int32_t can safely represent dates out to the year ~5.8 23 * million, making this format ideal for tracking coarse-grained time values 24 * like origin maintenance dates, and similar use cases. 25 * 26 * Internally, the date is derived from PR_Now(), which returns microseconds 27 * since the epoch. This ensures consistency with other quota-related timestamp 28 * logic, such as origin last access time. 29 */ 30 class Date final { 31 public: 32 static Date FromDays(int32_t aValue) { return Date(aValue); } 33 34 static Date FromTimestamp(int64_t aTimestamp) { 35 CheckedInt32 value = 36 (CheckedInt64(aTimestamp) / PR_USEC_PER_SEC / kSecPerDay) 37 .toChecked<int32_t>(); 38 MOZ_ASSERT(value.isValid()); 39 40 return Date(value.value()); 41 } 42 43 static Date Today() { return Date(FromTimestamp(PR_Now())); } 44 45 int32_t ToDays() const { return mValue; } 46 47 bool operator==(const Date& aOther) const { return mValue == aOther.mValue; } 48 bool operator!=(const Date& aOther) const { return mValue != aOther.mValue; } 49 bool operator<(const Date& aOther) const { return mValue < aOther.mValue; } 50 bool operator<=(const Date& aOther) const { return mValue <= aOther.mValue; } 51 bool operator>(const Date& aOther) const { return mValue > aOther.mValue; } 52 bool operator>=(const Date& aOther) const { return mValue >= aOther.mValue; } 53 54 private: 55 explicit Date(int32_t aValue) : mValue(aValue) {} 56 57 int32_t mValue; 58 }; 59 60 } // namespace mozilla::dom::quota 61 62 #endif // DOM_QUOTA_DATE_H_