2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "DateComponents.h"
34 #include "PlatformString.h"
36 #include <wtf/ASCIICType.h>
37 #include <wtf/DateMath.h>
38 #include <wtf/MathExtras.h>
44 // HTML5 uses ISO-8601 format with year >= 1. Gregorian calendar started in
45 // 1582. However, we need to support 0001-01-01 in Gregorian calendar rule.
46 static const int minimumYear = 1;
47 // Date in ECMAScript can't represent dates later than 275760-09-13T00:00Z.
48 // So, we have the same upper limit in HTML5 dates.
49 static const int maximumYear = 275760;
50 static const int maximumMonthInMaximumYear = 8; // This is September, since months are 0 based.
51 static const int maximumDayInMaximumMonth = 13;
52 static const int maximumWeekInMaximumYear = 37; // The week of 275760-09-13
54 static const int daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
56 static bool isLeapYear(int year)
67 // 'month' is 0-based.
68 static int maxDayOfMonth(int year, int month)
70 if (month != 1) // February?
71 return daysInMonth[month];
72 return isLeapYear(year) ? 29 : 28;
75 // 'month' is 0-based.
76 static int dayOfWeek(int year, int month, int day)
78 int shiftedMonth = month + 2;
79 // 2:January, 3:Feburuary, 4:March, ...
81 // Zeller's congruence
82 if (shiftedMonth <= 3) {
86 // 4:March, ..., 14:January, 15:February
88 int highYear = year / 100;
89 int lowYear = year % 100;
90 // We add 6 to make the result Sunday-origin.
91 int result = (day + 13 * shiftedMonth / 5 + lowYear + lowYear / 4 + highYear / 4 + 5 * highYear + 6) % 7;
95 int DateComponents::maxWeekNumberInYear() const
97 int day = dayOfWeek(m_year, 0, 1); // January 1.
98 return day == Thursday || (day == Wednesday && isLeapYear(m_year)) ? 53 : 52;
101 static unsigned countDigits(const UChar* src, unsigned length, unsigned start)
103 unsigned index = start;
104 for (; index < length; ++index) {
105 if (!isASCIIDigit(src[index]))
108 return index - start;
111 // Very strict integer parser. Do not allow leading or trailing whitespace unlike charactersToIntStrict().
112 static bool toInt(const UChar* src, unsigned length, unsigned parseStart, unsigned parseLength, int& out)
114 if (parseStart + parseLength > length || parseLength <= 0)
117 const UChar* current = src + parseStart;
118 const UChar* end = current + parseLength;
120 // We don't need to handle negative numbers for ISO 8601.
121 for (; current < end; ++current) {
122 if (!isASCIIDigit(*current))
124 int digit = *current - '0';
125 if (value > (INT_MAX - digit) / 10) // Check for overflow.
127 value = value * 10 + digit;
133 bool DateComponents::parseYear(const UChar* src, unsigned length, unsigned start, unsigned& end)
135 unsigned digitsLength = countDigits(src, length, start);
136 // Needs at least 4 digits according to the standard.
137 if (digitsLength < 4)
140 if (!toInt(src, length, start, digitsLength, year))
142 if (year < minimumYear || year > maximumYear)
145 end = start + digitsLength;
149 static bool withinHTMLDateLimits(int year, int month)
151 if (year < minimumYear)
153 if (year < maximumYear)
155 return month <= maximumMonthInMaximumYear;
158 static bool withinHTMLDateLimits(int year, int month, int monthDay)
160 if (year < minimumYear)
162 if (year < maximumYear)
164 if (month < maximumMonthInMaximumYear)
166 return monthDay <= maximumDayInMaximumMonth;
169 static bool withinHTMLDateLimits(int year, int month, int monthDay, int hour, int minute, int second, int millisecond)
171 if (year < minimumYear)
173 if (year < maximumYear)
175 if (month < maximumMonthInMaximumYear)
177 if (monthDay < maximumDayInMaximumMonth)
179 if (monthDay > maximumDayInMaximumMonth)
181 // (year, month, monthDay) = (maximumYear, maximumMonthInMaximumYear, maximumDayInMaximumMonth)
182 return !hour && !minute && !second && !millisecond;
185 bool DateComponents::addDay(int dayDiff)
189 int day = m_monthDay + dayDiff;
190 if (day > maxDayOfMonth(m_year, m_month)) {
194 int maxDay = maxDayOfMonth(year, month);
195 for (; dayDiff > 0; --dayDiff) {
200 if (month >= 12) { // month is 0-origin.
204 maxDay = maxDayOfMonth(year, month);
207 if (!withinHTMLDateLimits(year, month, day))
211 } else if (day < 1) {
215 for (; dayDiff < 0; ++dayDiff) {
223 day = maxDayOfMonth(year, month);
226 if (!withinHTMLDateLimits(year, month, day))
231 if (!withinHTMLDateLimits(m_year, m_month, day))
238 bool DateComponents::addMinute(int minute)
240 // This function is used to adjust timezone offset. So m_year, m_month,
241 // m_monthDay have values between the lower and higher limits.
242 ASSERT(withinHTMLDateLimits(m_year, m_month, m_monthDay));
245 // minute can be negative or greater than 59.
249 minute = minute % 60;
250 } else if (m_minute < 0) {
251 carry = (59 - m_minute) / 60;
252 minute += carry * 60;
254 ASSERT(minute >= 0 && minute <= 59);
256 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, minute, m_second, m_millisecond))
262 int hour = m_hour + carry;
266 } else if (hour < 0) {
267 carry = (23 - hour) / 24;
270 ASSERT(hour >= 0 && hour <= 23);
272 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, hour, minute, m_second, m_millisecond))
280 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, hour, minute, m_second, m_millisecond))
287 // Parses a timezone part, and adjust year, month, monthDay, hour, minute, second, millisecond.
288 bool DateComponents::parseTimeZone(const UChar* src, unsigned length, unsigned start, unsigned& end)
292 unsigned index = start;
293 if (src[index] == 'Z') {
299 if (src[index] == '+')
301 else if (src[index] == '-')
309 if (!toInt(src, length, index, 2, hour) || hour < 0 || hour > 23)
313 if (index >= length || src[index] != ':')
317 if (!toInt(src, length, index, 2, minute) || minute < 0 || minute > 59)
326 // Subtract the timezone offset.
327 if (!addMinute(-(hour * 60 + minute)))
333 bool DateComponents::parseMonth(const UChar* src, unsigned length, unsigned start, unsigned& end)
337 if (!parseYear(src, length, start, index))
339 if (index >= length || src[index] != '-')
344 if (!toInt(src, length, index, 2, month) || month < 1 || month > 12)
347 if (!withinHTMLDateLimits(m_year, month))
355 bool DateComponents::parseDate(const UChar* src, unsigned length, unsigned start, unsigned& end)
359 if (!parseMonth(src, length, start, index))
361 // '-' and 2-digits are needed.
362 if (index + 2 >= length)
364 if (src[index] != '-')
369 if (!toInt(src, length, index, 2, day) || day < 1 || day > maxDayOfMonth(m_year, m_month))
371 if (!withinHTMLDateLimits(m_year, m_month, day))
379 bool DateComponents::parseWeek(const UChar* src, unsigned length, unsigned start, unsigned& end)
383 if (!parseYear(src, length, start, index))
386 // 4 characters ('-' 'W' digit digit) are needed.
387 if (index + 3 >= length)
389 if (src[index] != '-')
392 if (src[index] != 'W')
397 if (!toInt(src, length, index, 2, week) || week < 1 || week > maxWeekNumberInYear())
399 if (m_year == maximumYear && week > maximumWeekInMaximumYear)
407 bool DateComponents::parseTime(const UChar* src, unsigned length, unsigned start, unsigned& end)
411 if (!toInt(src, length, start, 2, hour) || hour < 0 || hour > 23)
413 unsigned index = start + 2;
416 if (src[index] != ':')
421 if (!toInt(src, length, index, 2, minute) || minute < 0 || minute > 59)
427 // Optional second part.
428 // Do not return with false because the part is optional.
429 if (index + 2 < length && src[index] == ':') {
430 if (toInt(src, length, index + 1, 2, second) && second >= 0 && second <= 59) {
433 // Optional fractional second part.
434 if (index < length && src[index] == '.') {
435 unsigned digitsLength = countDigits(src, length, index + 1);
436 if (digitsLength > 0) {
439 if (digitsLength == 1) {
440 ok = toInt(src, length, index, 1, millisecond);
442 } else if (digitsLength == 2) {
443 ok = toInt(src, length, index, 2, millisecond);
445 } else // digitsLength >= 3
446 ok = toInt(src, length, index, 3, millisecond);
447 ASSERT_UNUSED(ok, ok);
448 index += digitsLength;
456 m_millisecond = millisecond;
462 bool DateComponents::parseDateTimeLocal(const UChar* src, unsigned length, unsigned start, unsigned& end)
466 if (!parseDate(src, length, start, index))
470 if (src[index] != 'T')
473 if (!parseTime(src, length, index, end))
475 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
477 m_type = DateTimeLocal;
481 bool DateComponents::parseDateTime(const UChar* src, unsigned length, unsigned start, unsigned& end)
485 if (!parseDate(src, length, start, index))
489 if (src[index] != 'T')
492 if (!parseTime(src, length, index, index))
494 if (!parseTimeZone(src, length, index, end))
496 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
502 static inline double positiveFmod(double value, double divider)
504 double remainder = fmod(value, divider);
505 return remainder < 0 ? remainder + divider : remainder;
508 void DateComponents::setMillisecondsSinceMidnightInternal(double msInDay)
510 ASSERT(msInDay >= 0 && msInDay < msPerDay);
511 m_millisecond = static_cast<int>(fmod(msInDay, msPerSecond));
512 double value = floor(msInDay / msPerSecond);
513 m_second = static_cast<int>(fmod(value, secondsPerMinute));
514 value = floor(value / secondsPerMinute);
515 m_minute = static_cast<int>(fmod(value, minutesPerHour));
516 m_hour = static_cast<int>(value / minutesPerHour);
519 bool DateComponents::setMillisecondsSinceEpochForDateInternal(double ms)
521 m_year = msToYear(ms);
522 int yearDay = dayInYear(ms, m_year);
523 m_month = monthFromDayInYear(yearDay, isLeapYear(m_year));
524 m_monthDay = dayInMonthFromDayInYear(yearDay, isLeapYear(m_year));
528 bool DateComponents::setMillisecondsSinceEpochForDate(double ms)
533 if (!setMillisecondsSinceEpochForDateInternal(round(ms)))
535 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay))
541 bool DateComponents::setMillisecondsSinceEpochForDateTime(double ms)
547 setMillisecondsSinceMidnightInternal(positiveFmod(ms, msPerDay));
548 if (!setMillisecondsSinceEpochForDateInternal(ms))
550 if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
556 bool DateComponents::setMillisecondsSinceEpochForDateTimeLocal(double ms)
558 // Internal representation of DateTimeLocal is the same as DateTime except m_type.
559 if (!setMillisecondsSinceEpochForDateTime(ms))
561 m_type = DateTimeLocal;
565 bool DateComponents::setMillisecondsSinceEpochForMonth(double ms)
570 if (!setMillisecondsSinceEpochForDateInternal(round(ms)))
572 if (!withinHTMLDateLimits(m_year, m_month))
578 bool DateComponents::setMillisecondsSinceMidnight(double ms)
583 setMillisecondsSinceMidnightInternal(positiveFmod(round(ms), msPerDay));
588 bool DateComponents::setMonthsSinceEpoch(double months)
590 if (!isfinite(months))
592 months = round(months);
593 double doubleMonth = positiveFmod(months, 12);
594 double doubleYear = 1970 + (months - doubleMonth) / 12;
595 if (doubleYear < minimumYear || maximumYear < doubleYear)
597 int year = static_cast<int>(doubleYear);
598 int month = static_cast<int>(doubleMonth);
599 if (!withinHTMLDateLimits(year, month))
607 // Offset from January 1st to Monday of the ISO 8601's first week.
608 // ex. If January 1st is Friday, such Monday is 3 days later. Returns 3.
609 static int offsetTo1stWeekStart(int year)
611 int offsetTo1stWeekStart = 1 - dayOfWeek(year, 0, 1);
612 if (offsetTo1stWeekStart <= -4)
613 offsetTo1stWeekStart += 7;
614 return offsetTo1stWeekStart;
617 bool DateComponents::setMillisecondsSinceEpochForWeek(double ms)
624 m_year = msToYear(ms);
625 if (m_year < minimumYear || m_year > maximumYear)
628 int yearDay = dayInYear(ms, m_year);
629 int offset = offsetTo1stWeekStart(m_year);
630 if (yearDay < offset) {
631 // The day belongs to the last week of the previous year.
633 if (m_year <= minimumYear)
635 m_week = maxWeekNumberInYear();
637 m_week = ((yearDay - offset) / 7) + 1;
638 if (m_week > maxWeekNumberInYear()) {
642 if (m_year > maximumYear || (m_year == maximumYear && m_week > maximumWeekInMaximumYear))
649 double DateComponents::millisecondsSinceEpochForTime() const
651 ASSERT(m_type == Time || m_type == DateTime || m_type == DateTimeLocal);
652 return ((m_hour * minutesPerHour + m_minute) * secondsPerMinute + m_second) * msPerSecond + m_millisecond;
655 double DateComponents::millisecondsSinceEpoch() const
659 return dateToDaysFrom1970(m_year, m_month, m_monthDay) * msPerDay;
662 return dateToDaysFrom1970(m_year, m_month, m_monthDay) * msPerDay + millisecondsSinceEpochForTime();
664 return dateToDaysFrom1970(m_year, m_month, 1) * msPerDay;
666 return millisecondsSinceEpochForTime();
668 return (dateToDaysFrom1970(m_year, 0, 1) + offsetTo1stWeekStart(m_year) + (m_week - 1) * 7) * msPerDay;
672 ASSERT_NOT_REACHED();
673 return invalidMilliseconds();
676 double DateComponents::monthsSinceEpoch() const
678 ASSERT(m_type == Month);
679 return (m_year - 1970) * 12 + m_month;
682 String DateComponents::toStringForTime(SecondFormat format) const
684 ASSERT(m_type == DateTime || m_type == DateTimeLocal || m_type == Time);
685 SecondFormat effectiveFormat = format;
687 effectiveFormat = Millisecond;
688 else if (format == None && m_second)
689 effectiveFormat = Second;
691 switch (effectiveFormat) {
693 ASSERT_NOT_REACHED();
696 return String::format("%02d:%02d", m_hour, m_minute);
698 return String::format("%02d:%02d:%02d", m_hour, m_minute, m_second);
700 return String::format("%02d:%02d:%02d.%03d", m_hour, m_minute, m_second, m_millisecond);
704 String DateComponents::toString(SecondFormat format) const
708 return String::format("%04d-%02d-%02d", m_year, m_month + 1, m_monthDay);
710 return String::format("%04d-%02d-%02dT", m_year, m_month + 1, m_monthDay)
711 + toStringForTime(format) + String("Z");
713 return String::format("%04d-%02d-%02dT", m_year, m_month + 1, m_monthDay)
714 + toStringForTime(format);
716 return String::format("%04d-%02d", m_year, m_month + 1);
718 return toStringForTime(format);
720 return String::format("%04d-W%02d", m_year, m_week);
724 ASSERT_NOT_REACHED();
725 return String("(Invalid DateComponents)");
728 } // namespace WebCore