| 155 | } |
| 156 | |
| 157 | bool DateValue::ToYear(int* year) const { |
| 158 | DCHECK(year != nullptr); |
| 159 | if (UNLIKELY(!IsValid())) return false; |
| 160 | |
| 161 | // This function was introduced to extract year of a DateValue efficiently. |
| 162 | // It will be fast for most days of the year and only slightly slower for days around |
| 163 | // the beginning and end of the year. |
| 164 | // |
| 165 | // Here's a quick explanation. Let's use the following notation: |
| 166 | // m400 = year % 400 |
| 167 | // m100 = m400 % 100 |
| 168 | // m4 = m100 % 4 |
| 169 | // |
| 170 | // If 'days' is the number of days between 1970-01-01 and the first day of 'year' |
| 171 | // (excluding the endpoint), then the following is true: |
| 172 | // days == (year - 1970) * 365 |
| 173 | // + ((year - 1968 + ((m4 != 0) ? 4 - m4 : 0)) / 4 - 1) |
| 174 | // - ((year - 1900 + ((m100 != 0) ? 100 - m100 : 0)) / 100 - 1) |
| 175 | // + ((year - 1600 + ((m400 != 0) ? 400 - m400 : 0)) / 400 - 1) |
| 176 | // |
| 177 | // Reordering the equation we get: |
| 178 | // days * 400 == (year - 1970) * 365 * 400 |
| 179 | // + ((year - 1968) * 100 + ((m4 != 0) ? (4 - m4) * 100 : 0) - 400) |
| 180 | // - ((year - 1900) * 4 + ((m100 != 0) ? (100 - m100) * 4 : 0) - 400) |
| 181 | // + (year - 1600 + ((m400 != 0) ? 400 - m400 : 0) - 400) |
| 182 | // |
| 183 | // then: |
| 184 | // days * 400 == year * 146000 - 287620000 |
| 185 | // + (year * 100 - 196800 + ((m4 != 0) ? (4 - m4) * 100 : 0) - 400) |
| 186 | // - (year * 4 - 7600 + ((m100 != 0) ? (100 - m100) * 4 : 0) - 400) |
| 187 | // + (year - 1600 + ((m400 != 0) ? 400 - m400 : 0) - 400) |
| 188 | // |
| 189 | // which means that (A): |
| 190 | // year * 146097 == days * 400 + 287811200 |
| 191 | // - ((m4 != 0) ? (4 - m4) * 100 : 0) |
| 192 | // + ((m100 != 0) ? (100 - m100) * 4 : 0) |
| 193 | // - ((m400 != 0) ? 400 - m400 : 0) |
| 194 | // |
| 195 | // On the other hand, if |
| 196 | // f(year) = - ((m4 != 0) ? (4 - m4) * 100 : 0) |
| 197 | // + ((m100 != 0) ? (100 - m100) * 4 : 0) |
| 198 | // - ((m400 != 0) ? 400 - m400 : 0) |
| 199 | // and 'year' is in the [1, 9999] range, then it follows that (B): |
| 200 | // f(year) must fall into the [-591, 288] range. |
| 201 | // |
| 202 | // Finally, if we put (A) and (B) together we can conclude that 'year' must fall into |
| 203 | // the |
| 204 | // [ (days * 400 + 287811200 - 591) / 146097, (days * 400 + 287811200 + 288) / 146097 ] |
| 205 | // range. |
| 206 | |
| 207 | int tmp = days_since_epoch_ * 400 + 287811200; |
| 208 | int first_year = (tmp - 591) / 146097; |
| 209 | int last_year = (tmp + 288) / 146097; |
| 210 | |
| 211 | if (first_year == last_year) { |
| 212 | *year = first_year; |
| 213 | } else if (CalcFirstDayOfYearSinceEpoch(last_year) <= days_since_epoch_) { |
| 214 | *year = last_year; |