Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(44)

Side by Side Diff: runtime/lib/date.dart

Issue 10834353: Reapply "Sharing of sources for corelib date implementation between VM (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Fix analyzer Created 8 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « lib/compiler/implementation/lib/coreimpl_patch.dart ('k') | runtime/lib/date_patch.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4 // Dart core library.
5
6 // VM implementation of DateImplementation.
7 class DateImplementation implements Date {
8 static final int _MAX_MILLISECONDS_SINCE_EPOCH = 8640000000000000;
9
10 DateImplementation(int years,
11 [int month = 1,
12 int day = 1,
13 int hour = 0,
14 int minute = 0,
15 int second = 0,
16 int millisecond = 0,
17 bool isUtc = false])
18 : this.isUtc = isUtc,
19 this.millisecondsSinceEpoch = _brokenDownDateToMillisecondsSinceEpoch(
20 years, month, day, hour, minute, second, millisecond, isUtc) {
21 if (millisecondsSinceEpoch === null) throw new IllegalArgumentException();
22 if (isUtc === null) throw new IllegalArgumentException();
23 }
24
25 DateImplementation.now()
26 : isUtc = false,
27 millisecondsSinceEpoch = _getCurrentMs() {
28 }
29
30 factory DateImplementation.fromString(String formattedString) {
31 // Read in (a subset of) ISO 8601.
32 // Examples:
33 // - "2012-02-27 13:27:00"
34 // - "2012-02-27 13:27:00.423z"
35 // - "20120227 13:27:00"
36 // - "20120227T132700"
37 // - "20120227"
38 // - "2012-02-27T14Z"
39 // - "-123450101 00:00:00 Z" // In the year -12345.
40 final RegExp re = const RegExp(
41 @'^([+-]?\d?\d\d\d\d)-?(\d\d)-?(\d\d)' // The day part.
42 @'(?:[ T](\d\d)(?::?(\d\d)(?::?(\d\d)(.\d{1,6})?)?)? ?([zZ])?)?$');
43 Match match = re.firstMatch(formattedString);
44 if (match !== null) {
45 int parseIntOrZero(String matched) {
46 // TODO(floitsch): we should not need to test against the empty string.
47 if (matched === null || matched == "") return 0;
48 return Math.parseInt(matched);
49 }
50
51 double parseDoubleOrZero(String matched) {
52 // TODO(floitsch): we should not need to test against the empty string.
53 if (matched === null || matched == "") return 0.0;
54 return Math.parseDouble(matched);
55 }
56
57 int years = Math.parseInt(match[1]);
58 int month = Math.parseInt(match[2]);
59 int day = Math.parseInt(match[3]);
60 int hour = parseIntOrZero(match[4]);
61 int minute = parseIntOrZero(match[5]);
62 int second = parseIntOrZero(match[6]);
63 bool addOneMillisecond = false;
64 int millisecond = (parseDoubleOrZero(match[7]) * 1000).round().toInt();
65 if (millisecond == 1000) {
66 addOneMillisecond = true;
67 millisecond = 999;
68 }
69 // TODO(floitsch): we should not need to test against the empty string.
70 bool isUtc = (match[8] !== null) && (match[8] != "");
71 int millisecondsSinceEpoch = _brokenDownDateToMillisecondsSinceEpoch(
72 years, month, day, hour, minute, second, millisecond, isUtc);
73 if (millisecondsSinceEpoch === null) {
74 throw new IllegalArgumentException(formattedString);
75 }
76 if (addOneMillisecond) millisecondsSinceEpoch++;
77 return new DateImplementation.fromMillisecondsSinceEpoch(
78 millisecondsSinceEpoch, isUtc);
79 } else {
80 throw new IllegalArgumentException(formattedString);
81 }
82 }
83
84 DateImplementation.fromMillisecondsSinceEpoch(
85 int this.millisecondsSinceEpoch, [bool isUtc = false])
86 : this.isUtc = isUtc {
87 if (millisecondsSinceEpoch.abs() > _MAX_MILLISECONDS_SINCE_EPOCH) {
88 throw new IllegalArgumentException(millisecondsSinceEpoch);
89 }
90 if (isUtc === null) {
91 throw new IllegalArgumentException(isUtc);
92 }
93 }
94
95 bool operator ==(Object other) {
96 if (other is !DateImplementation) return false;
97 DateImplementation otherDate = other;
98 return millisecondsSinceEpoch == otherDate.millisecondsSinceEpoch;
99 }
100
101 bool operator <(Date other)
102 => millisecondsSinceEpoch < other.millisecondsSinceEpoch;
103
104 bool operator <=(Date other)
105 => millisecondsSinceEpoch <= other.millisecondsSinceEpoch;
106
107 bool operator >(Date other)
108 => millisecondsSinceEpoch > other.millisecondsSinceEpoch;
109
110 bool operator >=(Date other)
111 => millisecondsSinceEpoch >= other.millisecondsSinceEpoch;
112
113 int compareTo(Date other)
114 => millisecondsSinceEpoch.compareTo(other.millisecondsSinceEpoch);
115
116 int hashCode() => millisecondsSinceEpoch;
117
118 Date toLocal() {
119 if (isUtc) {
120 return new DateImplementation.fromMillisecondsSinceEpoch(
121 millisecondsSinceEpoch, false);
122 }
123 return this;
124 }
125
126 Date toUtc() {
127 if (isUtc) return this;
128 return new DateImplementation.fromMillisecondsSinceEpoch(
129 millisecondsSinceEpoch, true);
130 }
131
132 String get timeZoneName() {
133 if (isUtc) return "UTC";
134 return _timeZoneName(millisecondsSinceEpoch);
135 }
136
137 Duration get timeZoneOffset() {
138 if (isUtc) return new Duration(0);
139 int offsetInSeconds = _timeZoneOffsetInSeconds(millisecondsSinceEpoch);
140 return new Duration(seconds: offsetInSeconds);
141 }
142
143 int get year() {
144 return _decomposeIntoYearMonthDay(_localDateInUtcMs)[0];
145 }
146
147 int get month() {
148 return _decomposeIntoYearMonthDay(_localDateInUtcMs)[1];
149 }
150
151 int get day() {
152 return _decomposeIntoYearMonthDay(_localDateInUtcMs)[2];
153 }
154
155 int get hour() {
156 int valueInHours = _flooredDivision(_localDateInUtcMs,
157 Duration.MILLISECONDS_PER_HOUR);
158 return valueInHours % Duration.HOURS_PER_DAY;
159 }
160
161 int get minute() {
162 int valueInMinutes = _flooredDivision(_localDateInUtcMs,
163 Duration.MILLISECONDS_PER_MINUTE);
164 return valueInMinutes % Duration.MINUTES_PER_HOUR;
165 }
166
167 int get second() {
168 // Seconds are unaffected by the timezone the user is in. So we can
169 // directly use the millisecondsSinceEpoch and not [_localDateInUtcMs].
170 int valueInSeconds =
171 _flooredDivision(millisecondsSinceEpoch,
172 Duration.MILLISECONDS_PER_SECOND);
173 return valueInSeconds % Duration.SECONDS_PER_MINUTE;
174 }
175
176 int get millisecond() {
177 // Milliseconds are unaffected by the timezone the user is in. So we can
178 // directly use the value and not the [_localDateInUtcValue].
179 return millisecondsSinceEpoch % Duration.MILLISECONDS_PER_SECOND;
180 }
181
182 /** Returns the weekday of [this]. In accordance with ISO 8601 a week
183 * starts with Monday. Monday has the value 1 up to Sunday with 7. */
184 int get weekday() {
185 int daysSince1970 =
186 _flooredDivision(_localDateInUtcMs, Duration.MILLISECONDS_PER_DAY);
187 // 1970-1-1 was a Thursday.
188 return ((daysSince1970 + Date.THU - Date.MON) % Date.DAYS_IN_WEEK) +
189 Date.MON;
190 }
191
192 String toString() {
193 String fourDigits(int n) {
194 int absN = n.abs();
195 String sign = n < 0 ? "-" : "";
196 if (absN >= 1000) return "$n";
197 if (absN >= 100) return "${sign}0$absN";
198 if (absN >= 10) return "${sign}00$absN";
199 return "${sign}000$absN";
200 }
201 String threeDigits(int n) {
202 if (n >= 100) return "${n}";
203 if (n >= 10) return "0${n}";
204 return "00${n}";
205 }
206 String twoDigits(int n) {
207 if (n >= 10) return "${n}";
208 return "0${n}";
209 }
210
211 String y = fourDigits(year);
212 String m = twoDigits(month);
213 String d = twoDigits(day);
214 String h = twoDigits(hour);
215 String min = twoDigits(minute);
216 String sec = twoDigits(second);
217 String ms = threeDigits(millisecond);
218 if (isUtc) {
219 return "$y-$m-$d $h:$min:$sec.${ms}Z";
220 } else {
221 return "$y-$m-$d $h:$min:$sec.$ms";
222 }
223 }
224
225 /** Returns a new [Date] with the [duration] added to [this]. */
226 Date add(Duration duration) {
227 int ms = millisecondsSinceEpoch;
228 return new DateImplementation.fromMillisecondsSinceEpoch(
229 ms + duration.inMilliseconds, isUtc);
230 }
231
232 /** Returns a new [Date] with the [duration] subtracted from [this]. */
233 Date subtract(Duration duration) {
234 int ms = millisecondsSinceEpoch;
235 return new DateImplementation.fromMillisecondsSinceEpoch(
236 ms - duration.inMilliseconds, isUtc);
237 }
238
239 /** Returns a [Duration] with the difference of [this] and [other]. */
240 Duration difference(Date other) {
241 int ms = millisecondsSinceEpoch;
242 int otherMs = other.millisecondsSinceEpoch;
243 return new DurationImplementation(milliseconds: ms - otherMs);
244 }
245
246 /** The first list contains the days until each month in non-leap years. The
247 * second list contains the days in leap years. */
248 static final List<List<int>> _DAYS_UNTIL_MONTH =
249 const [const [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
250 const [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]];
251
252 // Returns the UTC year, month and day for the corresponding
253 // [millisecondsSinceEpoch].
254 // Code is adapted from V8.
255 static List<int> _decomposeIntoYearMonthDay(int millisecondsSinceEpoch) {
256 // TODO(floitsch): cache result.
257 final int DAYS_IN_4_YEARS = 4 * 365 + 1;
258 final int DAYS_IN_100_YEARS = 25 * DAYS_IN_4_YEARS - 1;
259 final int DAYS_IN_400_YEARS = 4 * DAYS_IN_100_YEARS + 1;
260 final int DAYS_1970_TO_2000 = 30 * 365 + 7;
261 final int DAYS_OFFSET = 1000 * DAYS_IN_400_YEARS + 5 * DAYS_IN_400_YEARS -
262 DAYS_1970_TO_2000;
263 final int YEARS_OFFSET = 400000;
264
265 int resultYear = 0;
266 int resultMonth = 0;
267 int resultDay = 0;
268
269 // Always round down.
270 int days = _flooredDivision(millisecondsSinceEpoch,
271 Duration.MILLISECONDS_PER_DAY);
272 days += DAYS_OFFSET;
273 resultYear = 400 * (days ~/ DAYS_IN_400_YEARS) - YEARS_OFFSET;
274 days = days.remainder(DAYS_IN_400_YEARS);
275 days--;
276 int yd1 = days ~/ DAYS_IN_100_YEARS;
277 days = days.remainder(DAYS_IN_100_YEARS);
278 resultYear += 100 * yd1;
279 days++;
280 int yd2 = days ~/ DAYS_IN_4_YEARS;
281 days = days.remainder(DAYS_IN_4_YEARS);
282 resultYear += 4 * yd2;
283 days--;
284 int yd3 = days ~/ 365;
285 days = days.remainder(365);
286 resultYear += yd3;
287
288 bool isLeap = (yd1 == 0 || yd2 != 0) && yd3 == 0;
289 if (isLeap) days++;
290
291 List<int> daysUntilMonth = _DAYS_UNTIL_MONTH[isLeap ? 1 : 0];
292 for (resultMonth = 12;
293 daysUntilMonth[resultMonth - 1] > days;
294 resultMonth--) {
295 // Do nothing.
296 }
297 resultDay = days - daysUntilMonth[resultMonth - 1] + 1;
298 return <int>[resultYear, resultMonth, resultDay];
299 }
300
301 /**
302 * Returns the amount of milliseconds in UTC that represent the same values
303 * as [this].
304 *
305 * Say [:t:] is the result of this function, then
306 * * [:this.year == new Date.fromMillisecondsSinceEpoch(t, true).year:],
307 * * [:this.month == new Date.fromMillisecondsSinceEpoch(t, true).month:],
308 * * [:this.day == new Date.fromMillisecondsSinceEpoch(t, true).day:],
309 * * [:this.hour == new Date.fromMillisecondsSinceEpoch(t, true).hour:],
310 * * ...
311 *
312 * Daylight savings is computed as if the date was computed in [1970..2037].
313 * If [this] lies outside this range then it is a year with similar
314 * properties (leap year, weekdays) is used instead.
315 */
316 int get _localDateInUtcMs() {
317 int ms = millisecondsSinceEpoch;
318 if (isUtc) return ms;
319 int offset =
320 _timeZoneOffsetInSeconds(ms) * Duration.MILLISECONDS_PER_SECOND;
321 return ms + offset;
322 }
323
324 static int _flooredDivision(int a, int b) {
325 return (a - (a < 0 ? b - 1 : 0)) ~/ b;
326 }
327
328 // Returns the days since 1970 for the start of the given [year].
329 // [year] may be before epoch.
330 static int _dayFromYear(int year) {
331 return 365 * (year - 1970)
332 + _flooredDivision(year - 1969, 4)
333 - _flooredDivision(year - 1901, 100)
334 + _flooredDivision(year - 1601, 400);
335 }
336
337 static bool _isLeapYear(y) {
338 return (y.remainder(4) == 0) &&
339 ((y.remainder(100) != 0) || (y.remainder(400) == 0));
340 }
341
342 static _brokenDownDateToMillisecondsSinceEpoch(
343 int years, int month, int day,
344 int hour, int minute, int second, int millisecond,
345 bool isUtc) {
346 if ((month < 1) || (month > 12)) return null;
347 if ((day < 1) || (day > 31)) return null;
348 // Leap seconds can lead to hour == 24.
349 if ((hour < 0) || (hour > 24)) return null;
350 if ((hour == 24) && ((minute != 0) || (second != 0))) return null;
351 if ((minute < 0) || (minute > 59)) return null;
352 if ((second < 0) || (second > 59)) return null;
353 if ((millisecond < 0) || (millisecond > 999)) return null;
354
355 // First compute the seconds in UTC, independent of the [isUtc] flag. If
356 // necessary we will add the time-zone offset later on.
357 int days = day - 1;
358 days += _DAYS_UNTIL_MONTH[_isLeapYear(years) ? 1 : 0][month - 1];
359 days += _dayFromYear(years);
360 int millisecondsSinceEpoch = days * Duration.MILLISECONDS_PER_DAY +
361 hour * Duration.MILLISECONDS_PER_HOUR +
362 minute * Duration.MILLISECONDS_PER_MINUTE+
363 second * Duration.MILLISECONDS_PER_SECOND +
364 millisecond;
365
366 // Since [_timeZoneOffsetInSeconds] will crash if the input is far out of
367 // the valid range we do a preliminary test that weeds out values that can
368 // not become valid even with timezone adjustments.
369 // The timezone adjustment is always less than a day, so adding a security
370 // margin of one day should be enough.
371 if (millisecondsSinceEpoch.abs() >
372 (_MAX_MILLISECONDS_SINCE_EPOCH + Duration.MILLISECONDS_PER_DAY)) {
373 return null;
374 }
375
376 if (!isUtc) {
377 // Note that we need to remove the local timezone adjustement before
378 // asking for the correct zone offset.
379 int adjustment = _localTimeZoneAdjustmentInSeconds() *
380 Duration.MILLISECONDS_PER_SECOND;
381 int zoneOffset =
382 _timeZoneOffsetInSeconds(millisecondsSinceEpoch - adjustment);
383 millisecondsSinceEpoch -= zoneOffset * Duration.MILLISECONDS_PER_SECOND;
384 }
385 if (millisecondsSinceEpoch.abs() > _MAX_MILLISECONDS_SINCE_EPOCH) {
386 return null;
387 }
388 return millisecondsSinceEpoch;
389 }
390
391 /**
392 * Returns a year in the range 2008-2035 matching
393 * * leap year, and
394 * * week day of first day.
395 *
396 * Leap seconds are ignored.
397 * Adapted from V8's date implementation. See ECMA 262 - 15.9.1.9.
398 */
399 static _equivalentYear(int year) {
400 // Returns the week day (in range 0 - 6).
401 int weekDay(y) {
402 // 1/1/1970 was a Thursday.
403 return (_dayFromYear(y) + 4) % 7;
404 }
405 // 1/1/1956 was a Sunday (i.e. weekday 0). 1956 was a leap-year.
406 // 1/1/1967 was a Sunday (i.e. weekday 0).
407 // Without leap years a subsequent year has a week day + 1 (for example
408 // 1/1/1968 was a Monday). With leap-years it jumps over one week day
409 // (e.g. 1/1/1957 was a Tuesday).
410 // After 12 years the weekdays have advanced by 12 days + 3 leap days =
411 // 15 days. 15 % 7 = 1. So after 12 years the week day has always
412 // (now independently of leap-years) advanced by one.
413 // weekDay * 12 gives thus a year starting with the wanted weekDay.
414 int recentYear = (_isLeapYear(year) ? 1956 : 1967) + (weekDay(year) * 12);
415 // Close to the year 2008 the calendar cycles every 4 * 7 years (4 for the
416 // leap years, 7 for the weekdays).
417 // Find the year in the range 2008..2037 that is equivalent mod 28.
418 return 2008 + (recentYear - 2008) % 28;
419 }
420
421 /**
422 * Returns the UTC year for the corresponding [secondsSinceEpoch].
423 * It is relatively fast for values in the range 0 to year 2098.
424 *
425 * Code is adapted from V8.
426 */
427 static int _yearsFromSecondsSinceEpoch(int secondsSinceEpoch) {
428 final int DAYS_IN_4_YEARS = 4 * 365 + 1;
429 final int DAYS_IN_100_YEARS = 25 * DAYS_IN_4_YEARS - 1;
430 final int DAYS_YEAR_2098 = DAYS_IN_100_YEARS + 6 * DAYS_IN_4_YEARS;
431
432 int days = secondsSinceEpoch ~/ Duration.SECONDS_PER_DAY;
433 if (days > 0 && days < DAYS_YEAR_2098) {
434 // According to V8 this fast case works for dates from 1970 to 2099.
435 return 1970 + (4 * days + 2) ~/ DAYS_IN_4_YEARS;
436 }
437 int ms = secondsSinceEpoch * Duration.MILLISECONDS_PER_SECOND;
438 return _decomposeIntoYearMonthDay(ms)[0];
439 }
440
441 /**
442 * Returns a date in seconds that is equivalent to the current date. An
443 * equivalent date has the same fields ([:month:], [:day:], etc.) as the
444 * [this], but the [:year:] is in the range [1970..2037].
445 *
446 * * The time since the beginning of the year is the same.
447 * * If [this] is in a leap year then the returned seconds are in a leap
448 * year, too.
449 * * The week day of [this] is the same as the one for the returned date.
450 */
451 static int _equivalentSeconds(int millisecondsSinceEpoch) {
452 final int CUT_OFF_SECONDS = 2100000000;
453
454 int secondsSinceEpoch = _flooredDivision(millisecondsSinceEpoch,
455 Duration.MILLISECONDS_PER_SECOND);
456
457 if (secondsSinceEpoch < 0 || secondsSinceEpoch >= CUT_OFF_SECONDS) {
458 int year = _yearsFromSecondsSinceEpoch(secondsSinceEpoch);
459 int days = _dayFromYear(year);
460 int equivalentYear = _equivalentYear(year);
461 int equivalentDays = _dayFromYear(equivalentYear);
462 int diffDays = equivalentDays - days;
463 secondsSinceEpoch += diffDays * Duration.SECONDS_PER_DAY;
464 }
465 return secondsSinceEpoch;
466 }
467
468 static int _timeZoneOffsetInSeconds(int millisecondsSinceEpoch) {
469 int equivalentSeconds = _equivalentSeconds(millisecondsSinceEpoch);
470 return _timeZoneOffsetInSecondsForClampedSeconds(equivalentSeconds);
471 }
472
473 static String _timeZoneName(int millisecondsSinceEpoch) {
474 int equivalentSeconds = _equivalentSeconds(millisecondsSinceEpoch);
475 return _timeZoneNameForClampedSeconds(equivalentSeconds);
476 }
477
478 final bool isUtc;
479 final int millisecondsSinceEpoch;
480
481 // Natives
482 static int _getCurrentMs() native "DateNatives_currentTimeMillis";
483
484 static String _timeZoneNameForClampedSeconds(int secondsSinceEpoch)
485 native "DateNatives_timeZoneName";
486
487 static int _timeZoneOffsetInSecondsForClampedSeconds(int secondsSinceEpoch)
488 native "DateNatives_timeZoneOffsetInSeconds";
489
490 static int _localTimeZoneAdjustmentInSeconds()
491 native "DateNatives_localTimeZoneAdjustmentInSeconds";
492 }
OLDNEW
« no previous file with comments | « lib/compiler/implementation/lib/coreimpl_patch.dart ('k') | runtime/lib/date_patch.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698