Adding mapbox-gl branch

This commit is contained in:
Andreas Hocevar
2015-03-16 18:50:27 +01:00
parent 7985f030fa
commit 57ee7f52fd
3109 changed files with 943365 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<!--
Copyright 2006 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
Closure Unit Tests - goog.date
</title>
<script src="../base.js">
</script>
<script>
goog.require('goog.dateTest');
</script>
</head>
<body>
</body>
</html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Typedefs for working with dates.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.date.DateLike');
/**
* @typedef {(Date|goog.date.Date)}
*/
goog.date.DateLike;
@@ -0,0 +1,427 @@
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Date range data structure. Based loosely on
* com.google.common.util.DateRange.
*
*/
goog.provide('goog.date.DateRange');
goog.provide('goog.date.DateRange.Iterator');
goog.provide('goog.date.DateRange.StandardDateRangeKeys');
goog.require('goog.date.Date');
goog.require('goog.date.Interval');
goog.require('goog.iter.Iterator');
goog.require('goog.iter.StopIteration');
/**
* Constructs a date range.
* @constructor
* @param {goog.date.Date} startDate The first date in the range.
* @param {goog.date.Date} endDate The last date in the range.
* @final
*/
goog.date.DateRange = function(startDate, endDate) {
/**
* The first date in the range.
* @type {goog.date.Date}
* @private
*/
this.startDate_ = startDate;
/**
* The last date in the range.
* @type {goog.date.Date}
* @private
*/
this.endDate_ = endDate;
};
/**
* The first possible day, as far as this class is concerned.
* @type {goog.date.Date}
*/
goog.date.DateRange.MINIMUM_DATE = new goog.date.Date(0, 0, 1);
/**
* The last possible day, as far as this class is concerned.
* @type {goog.date.Date}
*/
goog.date.DateRange.MAXIMUM_DATE = new goog.date.Date(9999, 11, 31);
/**
* @return {goog.date.Date} The first date in the range.
*/
goog.date.DateRange.prototype.getStartDate = function() {
return this.startDate_;
};
/**
* @return {goog.date.Date} The last date in the range.
*/
goog.date.DateRange.prototype.getEndDate = function() {
return this.endDate_;
};
/**
* Tests if a date falls within this range.
*
* @param {goog.date.Date} date The date to test.
* @return {boolean} Whether the date is in the range.
*/
goog.date.DateRange.prototype.contains = function(date) {
return date.valueOf() >= this.startDate_.valueOf() &&
date.valueOf() <= this.endDate_.valueOf();
};
/**
* @return {!goog.iter.Iterator} An iterator over the date range.
*/
goog.date.DateRange.prototype.iterator = function() {
return new goog.date.DateRange.Iterator(this);
};
/**
* Tests two {@link goog.date.DateRange} objects for equality.
* @param {goog.date.DateRange} a A date range.
* @param {goog.date.DateRange} b A date range.
* @return {boolean} Whether |a| is the same range as |b|.
*/
goog.date.DateRange.equals = function(a, b) {
// Test for same object reference; type conversion is irrelevant.
if (a === b) {
return true;
}
if (a == null || b == null) {
return false;
}
return a.startDate_.equals(b.startDate_) && a.endDate_.equals(b.endDate_);
};
/**
* Calculates a date that is a number of days after a date. Does not modify its
* input.
* @param {goog.date.Date} date The input date.
* @param {number} offset Number of days.
* @return {!goog.date.Date} The date that is |offset| days after |date|.
* @private
*/
goog.date.DateRange.offsetInDays_ = function(date, offset) {
var newDate = date.clone();
newDate.add(new goog.date.Interval(goog.date.Interval.DAYS, offset));
return newDate;
};
/**
* Calculates the Monday before a date. If the input is a Monday, returns the
* input. Does not modify its input.
* @param {goog.date.Date} date The input date.
* @return {!goog.date.Date} If |date| is a Monday, return |date|; otherwise
* return the Monday before |date|.
* @private
*/
goog.date.DateRange.currentOrLastMonday_ = function(date) {
var newDate = date.clone();
newDate.add(new goog.date.Interval(goog.date.Interval.DAYS,
-newDate.getIsoWeekday()));
return newDate;
};
/**
* Calculates a date that is a number of months after the first day in the
* month that contains its input. Does not modify its input.
* @param {goog.date.Date} date The input date.
* @param {number} offset Number of months.
* @return {!goog.date.Date} The date that is |offset| months after the first
* day in the month that contains |date|.
* @private
*/
goog.date.DateRange.offsetInMonths_ = function(date, offset) {
var newDate = date.clone();
newDate.setDate(1);
newDate.add(new goog.date.Interval(goog.date.Interval.MONTHS, offset));
return newDate;
};
/**
* Returns the range from yesterday to yesterday.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that includes only yesterday.
*/
goog.date.DateRange.yesterday = function(opt_today) {
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
var yesterday = goog.date.DateRange.offsetInDays_(today, -1);
return new goog.date.DateRange(yesterday, yesterday);
};
/**
* Returns the range from today to today.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that includes only today.
*/
goog.date.DateRange.today = function(opt_today) {
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
return new goog.date.DateRange(today, today);
};
/**
* Returns the range that includes the seven days that end yesterday.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that includes the seven days that
* end yesterday.
*/
goog.date.DateRange.last7Days = function(opt_today) {
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
var yesterday = goog.date.DateRange.offsetInDays_(today, -1);
return new goog.date.DateRange(goog.date.DateRange.offsetInDays_(today, -7),
yesterday);
};
/**
* Returns the range that starts the first of this month and ends the last day
* of this month.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that starts the first of this month
* and ends the last day of this month.
*/
goog.date.DateRange.thisMonth = function(opt_today) {
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
return new goog.date.DateRange(
goog.date.DateRange.offsetInMonths_(today, 0),
goog.date.DateRange.offsetInDays_(
goog.date.DateRange.offsetInMonths_(today, 1),
-1));
};
/**
* Returns the range that starts the first of last month and ends the last day
* of last month.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that starts the first of last month
* and ends the last day of last month.
*/
goog.date.DateRange.lastMonth = function(opt_today) {
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
return new goog.date.DateRange(
goog.date.DateRange.offsetInMonths_(today, -1),
goog.date.DateRange.offsetInDays_(
goog.date.DateRange.offsetInMonths_(today, 0),
-1));
};
/**
* Returns the seven-day range that starts on the first day of the week
* (see {@link goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK}) on or before today.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that starts the Monday on or before
* today and ends the Sunday on or after today.
*/
goog.date.DateRange.thisWeek = function(opt_today) {
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
var iso = today.getIsoWeekday();
var firstDay = today.getFirstDayOfWeek();
var i18nFirstDay = (iso >= firstDay) ? iso - firstDay : iso + (7 - firstDay);
var start = goog.date.DateRange.offsetInDays_(today, -i18nFirstDay);
var end = goog.date.DateRange.offsetInDays_(start, 6);
return new goog.date.DateRange(start, end);
};
/**
* Returns the seven-day range that ends the day before the first day of
* the week (see {@link goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK}) that
* contains today.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that starts seven days before the
* Monday on or before today and ends the Sunday on or before yesterday.
*/
goog.date.DateRange.lastWeek = function(opt_today) {
var thisWeek = goog.date.DateRange.thisWeek(opt_today);
var start = goog.date.DateRange.offsetInDays_(thisWeek.getStartDate(), -7);
var end = goog.date.DateRange.offsetInDays_(thisWeek.getEndDate(), -7);
return new goog.date.DateRange(start, end);
};
/**
* Returns the range that starts seven days before the Monday on or before
* today and ends the Friday before today.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that starts seven days before the
* Monday on or before today and ends the Friday before today.
*/
goog.date.DateRange.lastBusinessWeek = function(opt_today) {
// TODO(user): should be i18nized.
var today = goog.date.DateRange.cloneOrCreate_(opt_today);
var start = goog.date.DateRange.offsetInDays_(today,
- 7 - today.getIsoWeekday());
var end = goog.date.DateRange.offsetInDays_(start, 4);
return new goog.date.DateRange(start, end);
};
/**
* Returns the range that includes all days between January 1, 1900 and
* December 31, 9999.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The range that includes all days between
* January 1, 1900 and December 31, 9999.
*/
goog.date.DateRange.allTime = function(opt_today) {
return new goog.date.DateRange(
goog.date.DateRange.MINIMUM_DATE,
goog.date.DateRange.MAXIMUM_DATE);
};
/**
* Standard date range keys. Equivalent to the enum IDs in
* DateRange.java http://go/datarange.java
*
* @enum {string}
*/
goog.date.DateRange.StandardDateRangeKeys = {
YESTERDAY: 'yesterday',
TODAY: 'today',
LAST_7_DAYS: 'last7days',
THIS_MONTH: 'thismonth',
LAST_MONTH: 'lastmonth',
THIS_WEEK: 'thisweek',
LAST_WEEK: 'lastweek',
LAST_BUSINESS_WEEK: 'lastbusinessweek',
ALL_TIME: 'alltime'
};
/**
* @param {string} dateRangeKey A standard date range key.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.DateRange} The date range that corresponds to that key.
* @throws {Error} If no standard date range with that key exists.
*/
goog.date.DateRange.standardDateRange = function(dateRangeKey, opt_today) {
switch (dateRangeKey) {
case goog.date.DateRange.StandardDateRangeKeys.YESTERDAY:
return goog.date.DateRange.yesterday(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.TODAY:
return goog.date.DateRange.today(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.LAST_7_DAYS:
return goog.date.DateRange.last7Days(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.THIS_MONTH:
return goog.date.DateRange.thisMonth(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.LAST_MONTH:
return goog.date.DateRange.lastMonth(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.THIS_WEEK:
return goog.date.DateRange.thisWeek(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.LAST_WEEK:
return goog.date.DateRange.lastWeek(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.LAST_BUSINESS_WEEK:
return goog.date.DateRange.lastBusinessWeek(opt_today);
case goog.date.DateRange.StandardDateRangeKeys.ALL_TIME:
return goog.date.DateRange.allTime(opt_today);
default:
throw Error('no such date range key: ' + dateRangeKey);
}
};
/**
* Clones or creates new.
* @param {goog.date.Date=} opt_today The date to consider today.
* Defaults to today.
* @return {!goog.date.Date} cloned or new.
* @private
*/
goog.date.DateRange.cloneOrCreate_ = function(opt_today) {
return opt_today ? opt_today.clone() : new goog.date.Date();
};
/**
* Creates an iterator over the dates in a {@link goog.date.DateRange}.
* @constructor
* @extends {goog.iter.Iterator}
* @param {goog.date.DateRange} dateRange The date range to iterate.
* @final
*/
goog.date.DateRange.Iterator = function(dateRange) {
/**
* The next date.
* @type {goog.date.Date}
* @private
*/
this.nextDate_ = dateRange.getStartDate().clone();
/**
* The end date, expressed as an integer: YYYYMMDD.
* @type {number}
* @private
*/
this.endDate_ = Number(dateRange.getEndDate().toIsoString());
};
goog.inherits(goog.date.DateRange.Iterator, goog.iter.Iterator);
/** @override */
goog.date.DateRange.Iterator.prototype.next = function() {
if (Number(this.nextDate_.toIsoString()) > this.endDate_) {
throw goog.iter.StopIteration;
}
var rv = this.nextDate_.clone();
this.nextDate_.add(new goog.date.Interval(goog.date.Interval.DAYS, 1));
return rv;
};
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<!--
Copyright 2006 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
Closure Unit Tests - gdr
</title>
<script src="../base.js">
</script>
<script>
goog.require('goog.date.DateRangeTest');
</script>
</head>
<body>
</body>
</html>
@@ -0,0 +1,258 @@
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.date.DateRangeTest');
goog.setTestOnly('goog.date.DateRangeTest');
goog.require('goog.date.Date');
goog.require('goog.date.DateRange');
goog.require('goog.date.Interval');
goog.require('goog.i18n.DateTimeSymbols');
goog.require('goog.testing.jsunit');
var gd = goog.date.Date;
var gdr = goog.date.DateRange;
var gdi = goog.date.Interval;
function testDateRange() {
var date1 = new gd(2000, 0, 1);
var date2 = new gd(2000, 1, 1);
var range = new gdr(date1, date2);
assertTrue('startDate matches', date1.equals(range.getStartDate()));
assertTrue('endDate matches', date2.equals(range.getEndDate()));
}
function testDateRangeEquals() {
var date1 = new gd(2000, 0, 1);
var date2 = new gd(2000, 1, 1);
var range1 = new gdr(date1, date2);
var range2 = new gdr(date1, date2);
assertTrue('equals', gdr.equals(range1, range2));
}
function testDateRangeNotEquals() {
var date1 = new gd(2000, 0, 1);
var date2 = new gd(2000, 1, 1);
var range1 = new gdr(date1, date2);
var range2 = new gdr(date2, date1);
assertFalse('not equals', gdr.equals(range1, range2));
}
function testOffsetInDays() {
var d = new gd(2000, 0, 1);
var f = gdr.offsetInDays_;
assertTrue('same day', d.equals(f(d, 0)));
assertTrue('next day', new gd(2000, 0, 2).equals(f(d, 1)));
assertTrue('last day', new gd(1999, 11, 31).equals(f(d, -1)));
}
function testCurrentOrLastMonday() {
var mon = new gd(2008, 9, 13);
var tue = new gd(2008, 9, 14);
var wed = new gd(2008, 9, 15);
var thu = new gd(2008, 9, 16);
var fri = new gd(2008, 9, 17);
var sat = new gd(2008, 9, 18);
var sun = new gd(2008, 9, 19);
var f = gdr.currentOrLastMonday_;
assertTrue('mon', mon.equals(f(mon)));
assertTrue('tue', mon.equals(f(tue)));
assertTrue('wed', mon.equals(f(wed)));
assertTrue('thu', mon.equals(f(thu)));
assertTrue('fri', mon.equals(f(fri)));
assertTrue('sat', mon.equals(f(sat)));
assertTrue('sun', mon.equals(f(sun)));
}
function testOffsetInMonths() {
var d = new gd(2008, 9, 13);
var f = gdr.offsetInMonths_;
assertTrue('this month', new gd(2008, 9, 1).equals(f(d, 0)));
assertTrue('last month', new gd(2008, 8, 1).equals(f(d, -1)));
assertTrue('next month', new gd(2008, 10, 1).equals(f(d, 1)));
assertTrue('next year', new gd(2009, 9, 1).equals(f(d, 12)));
assertTrue('last year', new gd(2007, 9, 1).equals(f(d, -12)));
}
function testYesterday() {
var d = new gd(2008, 9, 13);
var s = new gd(2008, 9, 12);
var e = new gd(2008, 9, 12);
assertStartEnd('yesterday', s, e, gdr.yesterday(d));
}
function testToday() {
var d = new gd(2008, 9, 13);
assertStartEnd('today', d, d, gdr.today(d));
}
function testLast7Days() {
var d = new gd(2008, 9, 13);
var s = new gd(2008, 9, 6);
var e = new gd(2008, 9, 12);
assertStartEnd('last7Days', s, e, gdr.last7Days(d));
assertStartEnd('last7Days by key', s, e,
gdr.standardDateRange(gdr.StandardDateRangeKeys.LAST_7_DAYS, d));
}
function testThisMonth() {
var d = new gd(2008, 9, 13);
var s = new gd(2008, 9, 1);
var e = new gd(2008, 9, 31);
assertStartEnd('thisMonth', s, e, gdr.thisMonth(d));
assertStartEnd('thisMonth by key', s, e,
gdr.standardDateRange(gdr.StandardDateRangeKeys.THIS_MONTH, d));
}
function testLastMonth() {
var d = new gd(2008, 9, 13);
var s = new gd(2008, 8, 1);
var e = new gd(2008, 8, 30);
assertStartEnd('lastMonth', s, e, gdr.lastMonth(d));
assertStartEnd('lastMonth by key', s, e,
gdr.standardDateRange(gdr.StandardDateRangeKeys.LAST_MONTH, d));
}
function testThisWeek() {
var startDates = [
new gd(2011, 2, 28),
new gd(2011, 2, 29),
new gd(2011, 2, 30),
new gd(2011, 2, 31),
new gd(2011, 3, 1),
new gd(2011, 2, 26),
new gd(2011, 2, 27)
];
var endDates = [
new gd(2011, 3, 3),
new gd(2011, 3, 4),
new gd(2011, 3, 5),
new gd(2011, 3, 6),
new gd(2011, 3, 7),
new gd(2011, 3, 1),
new gd(2011, 3, 2)
];
// 0 - is Monday, 6 is Sunday.
for (var i = 0; i < 7; i++) {
var date = new gd(2011, 3, 1);
date.setFirstDayOfWeek(i);
assertStartEnd('thisWeek, ' + i, startDates[i], endDates[i],
gdr.thisWeek(date));
}
assertStartEnd('thisWeek by key ',
startDates[goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK],
endDates[goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK],
gdr.standardDateRange(gdr.StandardDateRangeKeys.THIS_WEEK,
new gd(2011, 3, 1)));
}
function testLastWeek() {
var startDates = [
new gd(2011, 2, 21),
new gd(2011, 2, 22),
new gd(2011, 2, 23),
new gd(2011, 2, 24),
new gd(2011, 2, 25),
new gd(2011, 2, 19),
new gd(2011, 2, 20)
];
var endDates = [
new gd(2011, 2, 27),
new gd(2011, 2, 28),
new gd(2011, 2, 29),
new gd(2011, 2, 30),
new gd(2011, 2, 31),
new gd(2011, 2, 25),
new gd(2011, 2, 26)
];
// 0 - is Monday, 6 is Sunday.
for (var i = 0; i < 7; i++) {
var date = new gd(2011, 3, 1);
date.setFirstDayOfWeek(i);
assertStartEnd('lastWeek, ' + i, startDates[i], endDates[i],
gdr.lastWeek(date));
}
assertStartEnd('lastWeek by key',
startDates[goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK],
endDates[goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK],
gdr.standardDateRange(gdr.StandardDateRangeKeys.LAST_WEEK,
new gd(2011, 3, 1)));
}
function testLastBusinessWeek() {
var d = new gd(2008, 9, 13);
var s = new gd(2008, 9, 6);
var e = new gd(2008, 9, 10);
assertStartEnd('lastBusinessWeek', s, e, gdr.lastBusinessWeek(d));
assertStartEnd('lastBusinessWeek by key', s, e,
gdr.standardDateRange(gdr.StandardDateRangeKeys.LAST_BUSINESS_WEEK, d));
}
function testAllTime() {
var s = new gd(0000, 0, 1);
var e = new gd(9999, 11, 31);
assertStartEnd('allTime', s, e, gdr.allTime());
assertStartEnd('allTime by key', s, e,
gdr.standardDateRange(gdr.StandardDateRangeKeys.ALL_TIME));
}
function testIterator() {
var s = new gd(2008, 9, 1);
var e = new gd(2008, 9, 10);
var i = new gdr(s, e).iterator();
assertTrue('day 0', new gd(2008, 9, 1).equals(i.next()));
assertTrue('day 1', new gd(2008, 9, 2).equals(i.next()));
assertTrue('day 2', new gd(2008, 9, 3).equals(i.next()));
assertTrue('day 3', new gd(2008, 9, 4).equals(i.next()));
assertTrue('day 4', new gd(2008, 9, 5).equals(i.next()));
assertTrue('day 5', new gd(2008, 9, 6).equals(i.next()));
assertTrue('day 6', new gd(2008, 9, 7).equals(i.next()));
assertTrue('day 7', new gd(2008, 9, 8).equals(i.next()));
assertTrue('day 8', new gd(2008, 9, 9).equals(i.next()));
assertTrue('day 9', new gd(2008, 9, 10).equals(i.next()));
assertThrows('day 10', goog.bind(i.next, i));
}
function testContains() {
var r = new gdr(new gd(2008, 9, 10), new gd(2008, 9, 12));
assertFalse('min date', r.contains(goog.date.DateRange.MINIMUM_DATE));
assertFalse('9/10/2007', r.contains(new gd(2007, 9, 10)));
assertFalse('9/9/2008', r.contains(new gd(2008, 9, 9)));
assertTrue('9/10/2008', r.contains(new gd(2008, 9, 10)));
assertTrue('9/11/2008', r.contains(new gd(2008, 9, 11)));
assertTrue('9/12/2008', r.contains(new gd(2008, 9, 12)));
assertFalse('9/13/2008', r.contains(new gd(2008, 9, 13)));
assertFalse('max date', r.contains(goog.date.DateRange.MAXIMUM_DATE));
}
function assertStartEnd(name, start, end, actual) {
assertTrue(
name + ' start should be ' + start + ' but was ' + actual.getStartDate(),
start.equals(actual.getStartDate()));
assertTrue(
name + ' end should be ' + end + ' but was ' + actual.getEndDate(),
end.equals(actual.getEndDate()));
}
@@ -0,0 +1,153 @@
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Functions for formatting duration values. Such as "3 days"
* "3 hours", "14 minutes", "2 hours 45 minutes".
*
*/
goog.provide('goog.date.duration');
goog.require('goog.i18n.DateTimeFormat');
goog.require('goog.i18n.MessageFormat');
/**
* Number of milliseconds in a minute.
* @type {number}
* @private
*/
goog.date.duration.MINUTE_MS_ = 60000;
/**
* Number of milliseconds in an hour.
* @type {number}
* @private
*/
goog.date.duration.HOUR_MS_ = 3600000;
/**
* Number of milliseconds in a day.
* @type {number}
* @private
*/
goog.date.duration.DAY_MS_ = 86400000;
/**
* Accepts a duration in milliseconds and outputs an absolute duration time in
* form of "1 day", "2 hours", "20 minutes", "2 days 1 hour 15 minutes" etc.
* @param {number} durationMs Duration in milliseconds.
* @return {string} The formatted duration.
*/
goog.date.duration.format = function(durationMs) {
var ms = Math.abs(durationMs);
// Handle durations shorter than 1 minute.
if (ms < goog.date.duration.MINUTE_MS_) {
/**
* @desc Duration time of zero minutes.
*/
var MSG_ZERO_MINUTES = goog.getMsg('0 minutes');
return MSG_ZERO_MINUTES;
}
var days = Math.floor(ms / goog.date.duration.DAY_MS_);
ms %= goog.date.duration.DAY_MS_;
var hours = Math.floor(ms / goog.date.duration.HOUR_MS_);
ms %= goog.date.duration.HOUR_MS_;
var minutes = Math.floor(ms / goog.date.duration.MINUTE_MS_);
// Localized number representations.
var daysText = goog.i18n.DateTimeFormat.localizeNumbers(days);
var hoursText = goog.i18n.DateTimeFormat.localizeNumbers(hours);
var minutesText = goog.i18n.DateTimeFormat.localizeNumbers(minutes);
// We need a space after the days if there are hours or minutes to come.
var daysSeparator = days * (hours + minutes) ? ' ' : '';
// We need a space after the hours if there are minutes to come.
var hoursSeparator = hours * minutes ? ' ' : '';
/**
* @desc The days part of the duration message: 1 day, 5 days.
*/
var MSG_DURATION_DAYS = goog.getMsg(
'{COUNT, plural, ' +
'=0 {}' +
'=1 {{TEXT} day}' +
'other {{TEXT} days}}');
/**
* @desc The hours part of the duration message: 1 hour, 5 hours.
*/
var MSG_DURATION_HOURS = goog.getMsg(
'{COUNT, plural, ' +
'=0 {}' +
'=1 {{TEXT} hour}' +
'other {{TEXT} hours}}');
/**
* @desc The minutes part of the duration message: 1 minute, 5 minutes.
*/
var MSG_DURATION_MINUTES = goog.getMsg(
'{COUNT, plural, ' +
'=0 {}' +
'=1 {{TEXT} minute}' +
'other {{TEXT} minutes}}');
var daysPart = goog.date.duration.getDurationMessagePart_(
MSG_DURATION_DAYS, days, daysText);
var hoursPart = goog.date.duration.getDurationMessagePart_(
MSG_DURATION_HOURS, hours, hoursText);
var minutesPart = goog.date.duration.getDurationMessagePart_(
MSG_DURATION_MINUTES, minutes, minutesText);
/**
* @desc Duration time text concatenated from the individual time unit message
* parts. The separator will be a space (e.g. '1 day 2 hours 24 minutes') or
* nothing in case one/two of the duration parts is empty (
* e.g. '1 hour 30 minutes', '3 days 15 minutes', '2 hours').
*/
var MSG_CONCATENATED_DURATION_TEXT = goog.getMsg(
'{$daysPart}{$daysSeparator}{$hoursPart}{$hoursSeparator}{$minutesPart}',
{
'daysPart': daysPart,
'daysSeparator': daysSeparator,
'hoursPart': hoursPart,
'hoursSeparator': hoursSeparator,
'minutesPart': minutesPart
});
return MSG_CONCATENATED_DURATION_TEXT;
};
/**
* Gets a duration message part for a time unit.
* @param {string} pattern The pattern to apply.
* @param {number} count The number of units.
* @param {string} text The string to use for amount of units in the message.
* @return {string} The formatted message part.
* @private
*/
goog.date.duration.getDurationMessagePart_ = function(pattern, count, text) {
var formatter = new goog.i18n.MessageFormat(pattern);
return formatter.format({
'COUNT': count,
'TEXT': text
});
};
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<!--
-->
<html>
<!--
Copyright 2013 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
Test for goog.date.duration
</title>
<script src="../base.js">
</script>
<script>
goog.require('goog.date.durationTest');
</script>
</head>
<body>
</body>
</html>
@@ -0,0 +1,131 @@
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.LOCALE = 'en_US';
goog.provide('goog.date.durationTest');
goog.setTestOnly('goog.date.durationTest');
goog.require('goog.date.duration');
goog.require('goog.i18n.DateTimeFormat');
goog.require('goog.i18n.DateTimeSymbols');
goog.require('goog.i18n.DateTimeSymbols_bn'); // Bengali
goog.require('goog.i18n.DateTimeSymbols_en');
goog.require('goog.i18n.DateTimeSymbols_fa'); // Persian
goog.require('goog.testing.jsunit');
var MINUTE_MS = 60000;
var HOUR_MS = 60 * MINUTE_MS;
var DAY_MS = 24 * HOUR_MS;
var duration = goog.date.duration.format;
function testFormatDurationZeroMinutes() {
assertEquals('0 minutes', duration(0));
assertEquals('0 minutes', duration(MINUTE_MS - 1));
}
function testFormatDurationMinutes() {
assertEquals('1 minute', duration(MINUTE_MS));
assertEquals('1 minute', duration(MINUTE_MS + 1));
assertEquals('5 minutes', duration(5 * MINUTE_MS));
assertEquals('45 minutes', duration(45 * MINUTE_MS));
}
function testFormatDurationHours() {
assertEquals('1 hour', duration(HOUR_MS));
assertEquals('1 hour', duration(HOUR_MS + 1));
assertEquals('1 hour 1 minute', duration(HOUR_MS + MINUTE_MS));
assertEquals('1 hour 45 minutes', duration(HOUR_MS + 45 * MINUTE_MS));
assertEquals('5 hours', duration(5 * HOUR_MS));
assertEquals('5 hours', duration(5 * HOUR_MS + 1));
assertEquals('5 hours 1 minute', duration(5 * HOUR_MS + MINUTE_MS));
assertEquals('5 hours 45 minutes', duration(5 * HOUR_MS + 45 * MINUTE_MS));
assertEquals('11 hours', duration(11 * HOUR_MS));
assertEquals('11 hours', duration(11 * HOUR_MS + 1));
assertEquals('11 hours 1 minute', duration(11 * HOUR_MS + MINUTE_MS));
assertEquals('11 hours 45 minutes',
duration(11 * HOUR_MS + 45 * MINUTE_MS));
}
function testFormatDurationDays() {
assertEquals('1 day', duration(DAY_MS));
assertEquals('1 day', duration(DAY_MS + 1));
assertEquals('1 day 1 minute', duration(DAY_MS + MINUTE_MS));
assertEquals('1 day 45 minutes', duration(DAY_MS + 45 * MINUTE_MS));
assertEquals('1 day 1 hour', duration(DAY_MS + HOUR_MS));
assertEquals('1 day 11 hours', duration(DAY_MS + 11 * HOUR_MS));
assertEquals('1 day 1 hour 1 minute',
duration(DAY_MS + HOUR_MS + MINUTE_MS));
assertEquals('1 day 1 hour 45 minutes',
duration(DAY_MS + HOUR_MS + 45 * MINUTE_MS));
assertEquals('1 day 11 hours 1 minute',
duration(DAY_MS + 11 * HOUR_MS + MINUTE_MS));
assertEquals('1 day 11 hours 45 minutes',
duration(DAY_MS + 11 * HOUR_MS + 45 * MINUTE_MS));
assertEquals('11 days', duration(11 * DAY_MS));
assertEquals('11 days', duration(11 * DAY_MS + 1));
assertEquals('11 days 1 minute', duration(11 * DAY_MS + MINUTE_MS));
assertEquals('11 days 45 minutes', duration(11 * DAY_MS + 45 * MINUTE_MS));
assertEquals('11 days 1 hour', duration(11 * DAY_MS + HOUR_MS));
assertEquals('11 days 11 hours', duration(11 * DAY_MS + 11 * HOUR_MS));
assertEquals('11 days 1 hour 1 minute',
duration(11 * DAY_MS + HOUR_MS + MINUTE_MS));
assertEquals('11 days 1 hour 45 minutes',
duration(11 * DAY_MS + HOUR_MS + 45 * MINUTE_MS));
assertEquals('11 days 11 hours 1 minute',
duration(11 * DAY_MS + 11 * HOUR_MS + MINUTE_MS));
assertEquals('11 days 11 hours 45 minutes',
duration(11 * DAY_MS + 11 * HOUR_MS + 45 * MINUTE_MS));
}
function testFormatDurationPersianDigits() {
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_fa;
// ۱ minute
assertEquals(localizeNumber(1) + ' minute', duration(MINUTE_MS));
// ۲ minutes
assertEquals(localizeNumber(2) + ' minutes', duration(2 * MINUTE_MS));
// ۱۰ hours
assertEquals(localizeNumber(10) + ' hours', duration(10 * HOUR_MS));
// ۲۳ days
assertEquals(localizeNumber(23) + ' days', duration(23 * DAY_MS));
// Restore to English, to make sure we don't mess up other tests
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_en;
}
function testFormatDurationBengaliDigits() {
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_bn;
// ১ minute
assertEquals(localizeNumber(1) + ' minute', duration(MINUTE_MS));
// ২ minutes
assertEquals(localizeNumber(2) + ' minutes', duration(2 * MINUTE_MS));
// ১০ hours
assertEquals(localizeNumber(10) + ' hours', duration(10 * HOUR_MS));
// ২৩ days
assertEquals(localizeNumber(23) + ' days', duration(23 * DAY_MS));
// Restore to English, to make sure we don't mess up other tests
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_en;
}
function localizeNumber(value) {
// Quick conversion to national digits, to increase readability of the
// tests above.
return goog.i18n.DateTimeFormat.localizeNumbers(value);
}
@@ -0,0 +1,489 @@
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Functions for formatting relative dates. Such as "3 days ago"
* "3 hours ago", "14 minutes ago", "12 days ago", "Today", "Yesterday".
*
* For better quality localization of plurals ("hours"/"minutes"/"days") and
* to use local digits, goog.date.relativeWithPlurals can be loaded in addition
* to this namespace.
*
*/
goog.provide('goog.date.relative');
goog.provide('goog.date.relative.TimeDeltaFormatter');
goog.provide('goog.date.relative.Unit');
goog.require('goog.i18n.DateTimeFormat');
/**
* Number of milliseconds in a minute.
* @type {number}
* @private
*/
goog.date.relative.MINUTE_MS_ = 60000;
/**
* Number of milliseconds in a day.
* @type {number}
* @private
*/
goog.date.relative.DAY_MS_ = 86400000;
/**
* Enumeration used to identify time units internally.
* @enum {number}
*/
goog.date.relative.Unit = {
MINUTES: 0,
HOURS: 1,
DAYS: 2
};
/**
* Full date formatter.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.date.relative.fullDateFormatter_;
/**
* Short time formatter.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.date.relative.shortTimeFormatter_;
/**
* Month-date formatter.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.date.relative.monthDateFormatter_;
/**
* @typedef {function(number, boolean, goog.date.relative.Unit): string}
*/
goog.date.relative.TimeDeltaFormatter;
/**
* Handles formatting of time deltas.
* @private {goog.date.relative.TimeDeltaFormatter}
*/
goog.date.relative.formatTimeDelta_;
/**
* Sets a different formatting function for time deltas ("3 days ago").
* While its visibility is public, this function is Closure-internal and should
* not be used in application code.
* @param {goog.date.relative.TimeDeltaFormatter} formatter The function to use
* for formatting time deltas (i.e. relative times).
*/
goog.date.relative.setTimeDeltaFormatter = function(formatter) {
goog.date.relative.formatTimeDelta_ = formatter;
};
/**
* Returns a date in month format, e.g. Mar 15.
* @param {Date} date The date object.
* @return {string} The formatted string.
* @private
*/
goog.date.relative.formatMonth_ = function(date) {
if (!goog.date.relative.monthDateFormatter_) {
goog.date.relative.monthDateFormatter_ =
new goog.i18n.DateTimeFormat('MMM dd');
}
return goog.date.relative.monthDateFormatter_.format(date);
};
/**
* Returns a date in short-time format, e.g. 2:50 PM.
* @param {Date|goog.date.DateTime} date The date object.
* @return {string} The formatted string.
* @private
*/
goog.date.relative.formatShortTime_ = function(date) {
if (!goog.date.relative.shortTimeFormatter_) {
goog.date.relative.shortTimeFormatter_ = new goog.i18n.DateTimeFormat(
goog.i18n.DateTimeFormat.Format.SHORT_TIME);
}
return goog.date.relative.shortTimeFormatter_.format(date);
};
/**
* Returns a date in full date format, e.g. Tuesday, March 24, 2009.
* @param {Date|goog.date.DateTime} date The date object.
* @return {string} The formatted string.
* @private
*/
goog.date.relative.formatFullDate_ = function(date) {
if (!goog.date.relative.fullDateFormatter_) {
goog.date.relative.fullDateFormatter_ = new goog.i18n.DateTimeFormat(
goog.i18n.DateTimeFormat.Format.FULL_DATE);
}
return goog.date.relative.fullDateFormatter_.format(date);
};
/**
* Accepts a timestamp in milliseconds and outputs a relative time in the form
* of "1 hour ago", "1 day ago", "in 1 hour", "in 2 days" etc. If the date
* delta is over 2 weeks, then the output string will be empty.
* @param {number} dateMs Date in milliseconds.
* @return {string} The formatted date.
*/
goog.date.relative.format = function(dateMs) {
var now = goog.now();
var delta = Math.floor((now - dateMs) / goog.date.relative.MINUTE_MS_);
var future = false;
if (delta < 0) {
future = true;
delta *= -1;
}
if (delta < 60) { // Minutes.
return goog.date.relative.formatTimeDelta_(
delta, future, goog.date.relative.Unit.MINUTES);
} else {
delta = Math.floor(delta / 60);
if (delta < 24) { // Hours.
return goog.date.relative.formatTimeDelta_(
delta, future, goog.date.relative.Unit.HOURS);
} else {
// We can be more than 24 hours apart but still only 1 day apart, so we
// compare the closest time from today against the target time to find
// the number of days in the delta.
var midnight = new Date(goog.now());
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
midnight.setMilliseconds(0);
// Convert to days ago.
delta = Math.ceil(
(midnight.getTime() - dateMs) / goog.date.relative.DAY_MS_);
if (future) {
delta *= -1;
}
// Uses days for less than 2-weeks.
if (delta < 14) {
return goog.date.relative.formatTimeDelta_(
delta, future, goog.date.relative.Unit.DAYS);
} else {
// For messages older than 2 weeks do not show anything. The client
// should decide the date format to show.
return '';
}
}
}
};
/**
* Accepts a timestamp in milliseconds and outputs a relative time in the form
* of "1 hour ago", "1 day ago". All future times will be returned as 0 minutes
* ago.
*
* This is provided for compatibility with users of the previous incarnation of
* the above {@see #format} method who relied on it protecting against
* future dates.
*
* @param {number} dateMs Date in milliseconds.
* @return {string} The formatted date.
*/
goog.date.relative.formatPast = function(dateMs) {
var now = goog.now();
if (now < dateMs) {
dateMs = now;
}
return goog.date.relative.format(dateMs);
};
/**
* Accepts a timestamp in milliseconds and outputs a relative day. i.e. "Today",
* "Yesterday", "Tomorrow", or "Sept 15".
*
* @param {number} dateMs Date in milliseconds.
* @param {function(!Date):string=} opt_formatter Formatter for the date.
* Defaults to form 'MMM dd'.
* @return {string} The formatted date.
*/
goog.date.relative.formatDay = function(dateMs, opt_formatter) {
var today = new Date(goog.now());
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var yesterday = new Date(today.getTime() - goog.date.relative.DAY_MS_);
var tomorrow = new Date(today.getTime() + goog.date.relative.DAY_MS_);
var dayAfterTomorrow = new Date(today.getTime() +
2 * goog.date.relative.DAY_MS_);
var message;
if (dateMs >= tomorrow.getTime() && dateMs < dayAfterTomorrow.getTime()) {
/** @desc Tomorrow. */
var MSG_TOMORROW = goog.getMsg('Tomorrow');
message = MSG_TOMORROW;
} else if (dateMs >= today.getTime() && dateMs < tomorrow.getTime()) {
/** @desc Today. */
var MSG_TODAY = goog.getMsg('Today');
message = MSG_TODAY;
} else if (dateMs >= yesterday.getTime() && dateMs < today.getTime()) {
/** @desc Yesterday. */
var MSG_YESTERDAY = goog.getMsg('Yesterday');
message = MSG_YESTERDAY;
} else {
// If we don't have a special relative term for this date, then return the
// short date format (or a custom-formatted date).
var formatFunction = opt_formatter || goog.date.relative.formatMonth_;
message = formatFunction(new Date(dateMs));
}
return message;
};
/**
* Formats a date, adding the relative date in parenthesis. If the date is less
* than 24 hours then the time will be printed, otherwise the full-date will be
* used. Examples:
* 2:20 PM (1 minute ago)
* Monday, February 27, 2009 (4 days ago)
* Tuesday, March 20, 2005 // Too long ago for a relative date.
*
* @param {Date|goog.date.DateTime} date A date object.
* @param {string=} opt_shortTimeMsg An optional short time message can be
* provided if available, so that it's not recalculated in this function.
* @param {string=} opt_fullDateMsg An optional date message can be
* provided if available, so that it's not recalculated in this function.
* @return {string} The date string in the above form.
*/
goog.date.relative.getDateString = function(
date, opt_shortTimeMsg, opt_fullDateMsg) {
return goog.date.relative.getDateString_(
date, goog.date.relative.format, opt_shortTimeMsg, opt_fullDateMsg);
};
/**
* Formats a date, adding the relative date in parenthesis. Functions the same
* as #getDateString but ensures that the date is always seen to be in the past.
* If the date is in the future, it will be shown as 0 minutes ago.
*
* This is provided for compatibility with users of the previous incarnation of
* the above {@see #getDateString} method who relied on it protecting against
* future dates.
*
* @param {Date|goog.date.DateTime} date A date object.
* @param {string=} opt_shortTimeMsg An optional short time message can be
* provided if available, so that it's not recalculated in this function.
* @param {string=} opt_fullDateMsg An optional date message can be
* provided if available, so that it's not recalculated in this function.
* @return {string} The date string in the above form.
*/
goog.date.relative.getPastDateString = function(
date, opt_shortTimeMsg, opt_fullDateMsg) {
return goog.date.relative.getDateString_(
date, goog.date.relative.formatPast, opt_shortTimeMsg, opt_fullDateMsg);
};
/**
* Formats a date, adding the relative date in parenthesis. If the date is less
* than 24 hours then the time will be printed, otherwise the full-date will be
* used. Examples:
* 2:20 PM (1 minute ago)
* Monday, February 27, 2009 (4 days ago)
* Tuesday, March 20, 2005 // Too long ago for a relative date.
*
* @param {Date|goog.date.DateTime} date A date object.
* @param {function(number) : string} relativeFormatter Function to use when
* formatting the relative date.
* @param {string=} opt_shortTimeMsg An optional short time message can be
* provided if available, so that it's not recalculated in this function.
* @param {string=} opt_fullDateMsg An optional date message can be
* provided if available, so that it's not recalculated in this function.
* @return {string} The date string in the above form.
* @private
*/
goog.date.relative.getDateString_ = function(
date, relativeFormatter, opt_shortTimeMsg, opt_fullDateMsg) {
var dateMs = date.getTime();
var relativeDate = relativeFormatter(dateMs);
if (relativeDate) {
relativeDate = ' (' + relativeDate + ')';
}
var delta = Math.floor((goog.now() - dateMs) / goog.date.relative.MINUTE_MS_);
if (delta < 60 * 24) {
// TODO(user): this call raises an exception if date is a goog.date.Date.
return (opt_shortTimeMsg || goog.date.relative.formatShortTime_(date)) +
relativeDate;
} else {
return (opt_fullDateMsg || goog.date.relative.formatFullDate_(date)) +
relativeDate;
}
};
/*
* TODO(user):
*
* I think that this whole relative formatting should move to DateTimeFormat.
* But we would have to wait for the next version of CLDR, which is cleaning
* the data for relative dates (even ICU has incomplete support for this).
*/
/**
* Gets a localized relative date string for a given delta and unit.
* @param {number} delta Number of minutes/hours/days.
* @param {boolean} future Whether the delta is in the future.
* @param {goog.date.relative.Unit} unit The units the delta is in.
* @return {string} The message.
* @private
*/
goog.date.relative.getMessage_ = function(delta, future, unit) {
var deltaFormatted = goog.i18n.DateTimeFormat.localizeNumbers(delta);
if (!future && unit == goog.date.relative.Unit.MINUTES) {
/**
* @desc Relative date indicating how many minutes ago something happened
* (singular).
*/
var MSG_MINUTES_AGO_SINGULAR =
goog.getMsg('{$num} minute ago', {'num' : deltaFormatted});
/**
* @desc Relative date indicating how many minutes ago something happened
* (plural).
*/
var MSG_MINUTES_AGO_PLURAL =
goog.getMsg('{$num} minutes ago', {'num' : deltaFormatted});
return delta == 1 ? MSG_MINUTES_AGO_SINGULAR : MSG_MINUTES_AGO_PLURAL;
} else if (future && unit == goog.date.relative.Unit.MINUTES) {
/**
* @desc Relative date indicating in how many minutes something happens
* (singular).
*/
var MSG_IN_MINUTES_SINGULAR =
goog.getMsg('in {$num} minute', {'num' : deltaFormatted});
/**
* @desc Relative date indicating in how many minutes something happens
* (plural).
*/
var MSG_IN_MINUTES_PLURAL =
goog.getMsg('in {$num} minutes', {'num' : deltaFormatted});
return delta == 1 ? MSG_IN_MINUTES_SINGULAR : MSG_IN_MINUTES_PLURAL;
} else if (!future && unit == goog.date.relative.Unit.HOURS) {
/**
* @desc Relative date indicating how many hours ago something happened
* (singular).
*/
var MSG_HOURS_AGO_SINGULAR =
goog.getMsg('{$num} hour ago', {'num' : deltaFormatted});
/**
* @desc Relative date indicating how many hours ago something happened
* (plural).
*/
var MSG_HOURS_AGO_PLURAL =
goog.getMsg('{$num} hours ago', {'num' : deltaFormatted});
return delta == 1 ? MSG_HOURS_AGO_SINGULAR : MSG_HOURS_AGO_PLURAL;
} else if (future && unit == goog.date.relative.Unit.HOURS) {
/**
* @desc Relative date indicating in how many hours something happens
* (singular).
*/
var MSG_IN_HOURS_SINGULAR =
goog.getMsg('in {$num} hour', {'num' : deltaFormatted});
/**
* @desc Relative date indicating in how many hours something happens
* (plural).
*/
var MSG_IN_HOURS_PLURAL =
goog.getMsg('in {$num} hours', {'num' : deltaFormatted});
return delta == 1 ? MSG_IN_HOURS_SINGULAR : MSG_IN_HOURS_PLURAL;
} else if (!future && unit == goog.date.relative.Unit.DAYS) {
/**
* @desc Relative date indicating how many days ago something happened
* (singular).
*/
var MSG_DAYS_AGO_SINGULAR =
goog.getMsg('{$num} day ago', {'num' : deltaFormatted});
/**
* @desc Relative date indicating how many days ago something happened
* (plural).
*/
var MSG_DAYS_AGO_PLURAL =
goog.getMsg('{$num} days ago', {'num' : deltaFormatted});
return delta == 1 ? MSG_DAYS_AGO_SINGULAR : MSG_DAYS_AGO_PLURAL;
} else if (future && unit == goog.date.relative.Unit.DAYS) {
/**
* @desc Relative date indicating in how many days something happens
* (singular).
*/
var MSG_IN_DAYS_SINGULAR =
goog.getMsg('in {$num} day', {'num' : deltaFormatted});
/**
* @desc Relative date indicating in how many days something happens
* (plural).
*/
var MSG_IN_DAYS_PLURAL =
goog.getMsg('in {$num} days', {'num' : deltaFormatted});
return delta == 1 ? MSG_IN_DAYS_SINGULAR : MSG_IN_DAYS_PLURAL;
} else {
return '';
}
};
goog.date.relative.setTimeDeltaFormatter(goog.date.relative.getMessage_);
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<!--
-->
<html>
<!--
Copyright 2009 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
Test for goog.date.relative
</title>
<script src="../base.js">
</script>
<script>
goog.require('goog.date.relativeTest');
</script>
</head>
<body>
</body>
</html>
@@ -0,0 +1,163 @@
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.LOCALE = 'en_US';
goog.provide('goog.date.relativeTest');
goog.setTestOnly('goog.date.relativeTest');
goog.require('goog.date.DateTime');
goog.require('goog.date.relative');
goog.require('goog.i18n.DateTimeFormat');
goog.require('goog.testing.jsunit');
// Timestamp to base times for test on.
var baseTime = new Date(2009, 2, 23, 14, 31, 6).getTime();
// Ensure goog.now returns a constant timestamp.
goog.now = function() {
return baseTime;
};
function testFormatRelativeForPastDates() {
var fn = goog.date.relative.format;
assertEquals('Should round seconds to the minute below',
'0 minutes ago', fn(timestamp('23 March 2009 14:30:10')));
assertEquals('Should round seconds to the minute below',
'1 minute ago',
fn(timestamp('23 March 2009 14:29:56')));
assertEquals('Should round seconds to the minute below',
'2 minutes ago', fn(timestamp('23 March 2009 14:29:00')));
assertEquals('10 minutes ago', fn(timestamp('23 March 2009 14:20:10')));
assertEquals('59 minutes ago', fn(timestamp('23 March 2009 13:31:42')));
assertEquals('2 hours ago', fn(timestamp('23 March 2009 12:20:56')));
assertEquals('23 hours ago', fn(timestamp('22 March 2009 15:30:56')));
assertEquals('1 day ago', fn(timestamp('22 March 2009 12:11:04')));
assertEquals('1 day ago', fn(timestamp('22 March 2009 00:00:00')));
assertEquals('2 days ago', fn(timestamp('21 March 2009 23:59:59')));
assertEquals('2 days ago', fn(timestamp('21 March 2009 10:30:56')));
assertEquals('2 days ago', fn(timestamp('21 March 2009 00:00:00')));
assertEquals('3 days ago', fn(timestamp('20 March 2009 23:59:59')));
}
function testFormatRelativeForFutureDates() {
var fn = goog.date.relative.format;
assertEquals('Should round seconds to the minute below',
'in 1 minute',
fn(timestamp('23 March 2009 14:32:05')));
assertEquals('Should round seconds to the minute below',
'in 2 minutes', fn(timestamp('23 March 2009 14:33:00')));
assertEquals('in 10 minutes', fn(timestamp('23 March 2009 14:40:10')));
assertEquals('in 59 minutes', fn(timestamp('23 March 2009 15:29:15')));
assertEquals('in 2 hours', fn(timestamp('23 March 2009 17:20:56')));
assertEquals('in 23 hours', fn(timestamp('24 March 2009 13:30:56')));
assertEquals('in 1 day', fn(timestamp('24 March 2009 14:31:07')));
assertEquals('in 1 day', fn(timestamp('24 March 2009 16:11:04')));
assertEquals('in 1 day', fn(timestamp('24 March 2009 23:59:59')));
assertEquals('in 2 days', fn(timestamp('25 March 2009 00:00:00')));
assertEquals('in 2 days', fn(timestamp('25 March 2009 10:30:56')));
assertEquals('in 2 days', fn(timestamp('25 March 2009 23:59:59')));
assertEquals('in 3 days', fn(timestamp('26 March 2009 00:00:00')));
}
function testFormatPast() {
var fn = goog.date.relative.formatPast;
assertEquals('59 minutes ago', fn(timestamp('23 March 2009 13:31:42')));
assertEquals('0 minutes ago', fn(timestamp('23 March 2009 14:32:05')));
assertEquals('0 minutes ago', fn(timestamp('23 March 2009 14:33:00')));
assertEquals('0 minutes ago', fn(timestamp('25 March 2009 10:30:56')));
}
function testFormatDay() {
var fn = goog.date.relative.formatDay;
var formatter = new goog.i18n.DateTimeFormat(
goog.i18n.DateTimeFormat.Format.SHORT_DATE);
var format = goog.bind(formatter.format, formatter);
assertEquals('Sep 25', fn(timestamp('25 September 2009 10:31:06')));
assertEquals('Mar 25', fn(timestamp('25 March 2009 00:12:19')));
assertEquals('Tomorrow', fn(timestamp('24 March 2009 10:31:06')));
assertEquals('Tomorrow', fn(timestamp('24 March 2009 00:12:19')));
assertEquals('Today', fn(timestamp('23 March 2009 10:31:06')));
assertEquals('Today', fn(timestamp('23 March 2009 00:12:19')));
assertEquals('Yesterday', fn(timestamp('22 March 2009 23:48:12')));
assertEquals('Yesterday', fn(timestamp('22 March 2009 04:11:23')));
assertEquals('Mar 21', fn(timestamp('21 March 2009 15:54:45')));
assertEquals('Mar 19', fn(timestamp('19 March 2009 01:22:11')));
// Test that a formatter can also be accepted as input.
assertEquals('Today', fn(timestamp('23 March 2009 10:31:06'), format));
assertEquals('Today', fn(timestamp('23 March 2009 00:12:19'), format));
assertEquals('Yesterday', fn(timestamp('22 March 2009 23:48:12'), format));
assertEquals('Yesterday', fn(timestamp('22 March 2009 04:11:23'), format));
assertEquals(format(gdatetime(timestamp('21 March 2009 15:54:45'))),
fn(timestamp('21 March 2009 15:54:45'), format));
assertEquals(format(gdatetime(timestamp('19 March 2009 01:22:11'))),
fn(timestamp('19 March 2009 01:22:11'), format));
}
function testGetDateString() {
var fn = goog.date.relative.getDateString;
assertEquals('2:21 PM (10 minutes ago)',
fn(new Date(baseTime - 10 * 60 * 1000)));
assertEquals('4:31 AM (10 hours ago)',
fn(new Date(baseTime - 10 * 60 * 60 * 1000)));
assertEquals('Friday, March 13, 2009 (10 days ago)',
fn(new Date(baseTime - 10 * 24 * 60 * 60 * 1000)));
assertEquals('Tuesday, March 3, 2009',
fn(new Date(baseTime - 20 * 24 * 60 * 60 * 1000)));
// Test that goog.date.DateTime can also be accepted as input.
assertEquals('2:21 PM (10 minutes ago)',
fn(gdatetime(baseTime - 10 * 60 * 1000)));
assertEquals('4:31 AM (10 hours ago)',
fn(gdatetime(baseTime - 10 * 60 * 60 * 1000)));
assertEquals('Friday, March 13, 2009 (10 days ago)',
fn(gdatetime(baseTime - 10 * 24 * 60 * 60 * 1000)));
assertEquals('Tuesday, March 3, 2009',
fn(gdatetime(baseTime - 20 * 24 * 60 * 60 * 1000)));
}
function testGetPastDateString() {
var fn = goog.date.relative.getPastDateString;
assertEquals('2:21 PM (10 minutes ago)',
fn(new Date(baseTime - 10 * 60 * 1000)));
assertEquals('2:41 PM (0 minutes ago)',
fn(new Date(baseTime + 10 * 60 * 1000)));
// Test that goog.date.DateTime can also be accepted as input.
assertEquals('2:21 PM (10 minutes ago)',
fn(gdatetime(baseTime - 10 * 60 * 1000)));
assertEquals('2:41 PM (0 minutes ago)',
fn(gdatetime(baseTime + 10 * 60 * 1000)));
}
function gdatetime(timestamp) {
return new goog.date.DateTime(new Date(timestamp));
}
function timestamp(str) {
return new Date(str).getTime();
}
@@ -0,0 +1,120 @@
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Code to make goog.date.relative plurals-aware.
*/
goog.provide('goog.date.relativeWithPlurals');
goog.require('goog.date.relative');
goog.require('goog.date.relative.Unit');
goog.require('goog.i18n.MessageFormat');
/**
* Gets a localized relative date string for a given delta and unit.
* @param {number} delta Number of minutes/hours/days.
* @param {boolean} future Whether the delta is in the future.
* @param {goog.date.relative.Unit} unit The units the delta is in.
* @return {string} The message.
* @private
*/
goog.date.relativeWithPlurals.formatTimeDelta_ =
function(delta, future, unit) {
if (!future && unit == goog.date.relative.Unit.MINUTES) {
/**
* @desc Relative date indicating how many minutes ago something happened.
*/
var MSG_MINUTES_AGO_ICU =
goog.getMsg('{NUM, plural, ' +
'=0 {# minutes ago}' +
'=1 {# minute ago}' +
'other {# minutes ago}}');
return new goog.i18n.MessageFormat(MSG_MINUTES_AGO_ICU).
format({'NUM': delta});
} else if (future && unit == goog.date.relative.Unit.MINUTES) {
/**
* @desc Relative date indicating in how many minutes something happens.
*/
var MSG_IN_MINUTES_ICU =
goog.getMsg('{NUM, plural, ' +
'=0 {in # minutes}' +
'=1 {in # minute}' +
'other {in # minutes}}');
return new goog.i18n.MessageFormat(MSG_IN_MINUTES_ICU).
format({'NUM': delta});
} else if (!future && unit == goog.date.relative.Unit.HOURS) {
/**
* @desc Relative date indicating how many hours ago something happened.
*/
var MSG_HOURS_AGO_ICU =
goog.getMsg('{NUM, plural, ' +
'=0 {# hours ago}' +
'=1 {# hour ago}' +
'other {# hours ago}}');
return new goog.i18n.MessageFormat(MSG_HOURS_AGO_ICU).
format({'NUM': delta});
} else if (future && unit == goog.date.relative.Unit.HOURS) {
/**
* @desc Relative date indicating in how many hours something happens.
*/
var MSG_IN_HOURS_ICU =
goog.getMsg('{NUM, plural, ' +
'=0 {in # hours}' +
'=1 {in # hour}' +
'other {in # hours}}');
return new goog.i18n.MessageFormat(MSG_IN_HOURS_ICU).
format({'NUM': delta});
} else if (!future && unit == goog.date.relative.Unit.DAYS) {
/**
* @desc Relative date indicating how many days ago something happened.
*/
var MSG_DAYS_AGO_ICU =
goog.getMsg('{NUM, plural, ' +
'=0 {# days ago}' +
'=1 {# day ago}' +
'other {# days ago}}');
return new goog.i18n.MessageFormat(MSG_DAYS_AGO_ICU).
format({'NUM': delta});
} else if (future && unit == goog.date.relative.Unit.DAYS) {
/**
* @desc Relative date indicating in how many days something happens.
*/
var MSG_IN_DAYS_ICU =
goog.getMsg('{NUM, plural, ' +
'=0 {in # days}' +
'=1 {in # day}' +
'other {in # days}}');
return new goog.i18n.MessageFormat(MSG_IN_DAYS_ICU).
format({'NUM': delta});
} else {
return '';
}
};
goog.date.relative.setTimeDeltaFormatter(
goog.date.relativeWithPlurals.formatTimeDelta_);
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<!--
-->
<html>
<!--
Copyright 2009 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
Test for goog.date.relativeWithPlurals
</title>
<script src="../base.js">
</script>
<script>
goog.require('goog.date.relativeWithPluralsTest');
</script>
</head>
<body>
</body>
</html>
@@ -0,0 +1,128 @@
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.date.relativeWithPluralsTest');
goog.setTestOnly('goog.date.relativeWithPluralsTest');
goog.require('goog.date.relative');
/** @suppress {extraRequire} Include shared tests. */
goog.require('goog.date.relativeTest');
/** @suppress {extraRequire} Included for side effects. */
goog.require('goog.date.relativeWithPlurals');
goog.require('goog.i18n.DateTimeFormat');
goog.require('goog.i18n.DateTimeSymbols');
goog.require('goog.i18n.DateTimeSymbols_bn'); // Bengali
goog.require('goog.i18n.DateTimeSymbols_en');
goog.require('goog.i18n.DateTimeSymbols_fa'); // Persian
goog.require('goog.i18n.NumberFormatSymbols');
goog.require('goog.i18n.NumberFormatSymbols_bn'); // Bengali
goog.require('goog.i18n.NumberFormatSymbols_en');
goog.require('goog.i18n.NumberFormatSymbols_fa'); // Persian
function tearDown() {
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_en;
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
function testFormatRelativeForPastDatesPersianDigits() {
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_fa;
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fa;
var fn = goog.date.relative.format;
// The text here is English, as it comes from localized resources, not
// from CLDR. It works properly in production, but it's not loaded here.
// Will need to wait for CLDR 24, when the data we need will be available,
// so that we can add it to DateTimeSymbols and out of localization.
// For Persian \u06F0 is the base, so \u6F0 = digit 0, \u6F5 = digit 5 ...
// "Western" digits in square brackets for convenience
assertEquals('Should round seconds to the minute below',
localizeNumber(0) + ' minutes ago', // ۰ minutes ago
fn(timestamp('23 March 2009 14:30:10')));
assertEquals('Should round seconds to the minute below',
localizeNumber(1) + ' minute ago', // ۱ minute ago
fn(timestamp('23 March 2009 14:29:56')));
assertEquals('Should round seconds to the minute below',
localizeNumber(2) + ' minutes ago', // ۲ minutes ago
fn(timestamp('23 March 2009 14:29:00')));
assertEquals(localizeNumber(10) + ' minutes ago', // ۱۰ minutes ago
fn(timestamp('23 March 2009 14:20:10')));
assertEquals(localizeNumber(59) + ' minutes ago', // ۵۹ minutes ago
fn(timestamp('23 March 2009 13:31:42')));
assertEquals(localizeNumber(2) + ' hours ago', // ۲ hours ago
fn(timestamp('23 March 2009 12:20:56')));
assertEquals(localizeNumber(23) + ' hours ago', // ۲۳ hours ago
fn(timestamp('22 March 2009 15:30:56')));
assertEquals(localizeNumber(1) + ' day ago', // ۱ day ago
fn(timestamp('22 March 2009 12:11:04')));
assertEquals(localizeNumber(1) + ' day ago', // ۱ day ago
fn(timestamp('22 March 2009 00:00:00')));
assertEquals(localizeNumber(2) + ' days ago', // ۲ days ago
fn(timestamp('21 March 2009 23:59:59')));
assertEquals(localizeNumber(2) + ' days ago', // ۲ days ago
fn(timestamp('21 March 2009 10:30:56')));
assertEquals(localizeNumber(2) + ' days ago', // ۲ days ago
fn(timestamp('21 March 2009 00:00:00')));
assertEquals(localizeNumber(3) + ' days ago', // ۳ days ago
fn(timestamp('20 March 2009 23:59:59')));
}
function testFormatRelativeForFutureDatesBengaliDigits() {
var fn = goog.date.relative.format;
goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_bn;
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_bn;
// For Bengali \u09E6 is the base, so \u09E6 = digit 0, \u09EB = digit 5
// "Western" digits in square brackets for convenience
assertEquals('Should round seconds to the minute below',
'in ' + localizeNumber(1) + ' minute', // in ১ minute
fn(timestamp('23 March 2009 14:32:05')));
assertEquals('Should round seconds to the minute below',
'in ' + localizeNumber(2) + ' minutes', // in ২ minutes
fn(timestamp('23 March 2009 14:33:00')));
assertEquals('in ' + localizeNumber(10) + ' minutes', // in ১০ minutes
fn(timestamp('23 March 2009 14:40:10')));
assertEquals('in ' + localizeNumber(59) + ' minutes', // in ৫৯ minutes
fn(timestamp('23 March 2009 15:29:15')));
assertEquals('in ' + localizeNumber(2) + ' hours', // in ২ hours
fn(timestamp('23 March 2009 17:20:56')));
assertEquals('in ' + localizeNumber(23) + ' hours', // in ২৩ hours
fn(timestamp('24 March 2009 13:30:56')));
assertEquals('in ' + localizeNumber(1) + ' day', // in ১ day
fn(timestamp('24 March 2009 14:31:07')));
assertEquals('in ' + localizeNumber(1) + ' day', // in ১ day
fn(timestamp('24 March 2009 16:11:04')));
assertEquals('in ' + localizeNumber(1) + ' day', // in ১ day
fn(timestamp('24 March 2009 23:59:59')));
assertEquals('in ' + localizeNumber(2) + ' days', // in ২ days
fn(timestamp('25 March 2009 00:00:00')));
assertEquals('in ' + localizeNumber(2) + ' days', // in ২ days
fn(timestamp('25 March 2009 10:30:56')));
assertEquals('in ' + localizeNumber(2) + ' days', // in ২ days
fn(timestamp('25 March 2009 23:59:59')));
assertEquals('in ' + localizeNumber(3) + ' days', // in ৩ days
fn(timestamp('26 March 2009 00:00:00')));
}
function localizeNumber(value) {
// Quick conversion to national digits, to increase readability of the
// tests above.
return goog.i18n.DateTimeFormat.localizeNumbers(value);
}
@@ -0,0 +1,190 @@
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Locale independent date/time class.
*
*/
goog.provide('goog.date.UtcDateTime');
goog.require('goog.date');
goog.require('goog.date.Date');
goog.require('goog.date.DateTime');
goog.require('goog.date.Interval');
/**
* Class representing a date/time in GMT+0 time zone, without daylight saving.
* Defaults to current date and time if none is specified. The get... and the
* getUTC... methods are equivalent.
*
* @param {number|goog.date.DateLike=} opt_year Four digit UTC year or a
* date-like object. If not set, the created object will contain the
* date determined by goog.now().
* @param {number=} opt_month UTC month, 0 = Jan, 11 = Dec.
* @param {number=} opt_date UTC date of month, 1 - 31.
* @param {number=} opt_hours UTC hours, 0 - 23.
* @param {number=} opt_minutes UTC minutes, 0 - 59.
* @param {number=} opt_seconds UTC seconds, 0 - 59.
* @param {number=} opt_milliseconds UTC milliseconds, 0 - 999.
* @constructor
* @extends {goog.date.DateTime}
*/
goog.date.UtcDateTime = function(opt_year, opt_month, opt_date, opt_hours,
opt_minutes, opt_seconds, opt_milliseconds) {
var timestamp;
if (goog.isNumber(opt_year)) {
timestamp = Date.UTC(opt_year, opt_month || 0, opt_date || 1,
opt_hours || 0, opt_minutes || 0, opt_seconds || 0,
opt_milliseconds || 0);
} else {
timestamp = opt_year ? opt_year.getTime() : goog.now();
}
this.date = new Date(timestamp);
};
goog.inherits(goog.date.UtcDateTime, goog.date.DateTime);
/**
* @param {number} timestamp Number of milliseconds since Epoch.
* @return {!goog.date.UtcDateTime}
*/
goog.date.UtcDateTime.fromTimestamp = function(timestamp) {
var date = new goog.date.UtcDateTime();
date.setTime(timestamp);
return date;
};
/**
* Creates a DateTime from a UTC datetime string expressed in ISO 8601 format.
*
* @param {string} formatted A date or datetime expressed in ISO 8601 format.
* @return {goog.date.UtcDateTime} Parsed date or null if parse fails.
*/
goog.date.UtcDateTime.fromIsoString = function(formatted) {
var ret = new goog.date.UtcDateTime(2000);
return goog.date.setIso8601DateTime(ret, formatted) ? ret : null;
};
/**
* Clones the UtcDateTime object.
*
* @return {!goog.date.UtcDateTime} A clone of the datetime object.
* @override
*/
goog.date.UtcDateTime.prototype.clone = function() {
var date = new goog.date.UtcDateTime(this.date);
date.setFirstDayOfWeek(this.getFirstDayOfWeek());
date.setFirstWeekCutOffDay(this.getFirstWeekCutOffDay());
return date;
};
/** @override */
goog.date.UtcDateTime.prototype.add = function(interval) {
if (interval.years || interval.months) {
var yearsMonths = new goog.date.Interval(interval.years, interval.months);
goog.date.Date.prototype.add.call(this, yearsMonths);
}
var daysAndTimeMillis = 1000 * (
interval.seconds + 60 * (
interval.minutes + 60 * (
interval.hours + 24 * interval.days)));
this.date = new Date(this.date.getTime() + daysAndTimeMillis);
};
/** @override */
goog.date.UtcDateTime.prototype.getTimezoneOffset = function() {
return 0;
};
/** @override */
goog.date.UtcDateTime.prototype.getFullYear =
goog.date.DateTime.prototype.getUTCFullYear;
/** @override */
goog.date.UtcDateTime.prototype.getMonth =
goog.date.DateTime.prototype.getUTCMonth;
/** @override */
goog.date.UtcDateTime.prototype.getDate =
goog.date.DateTime.prototype.getUTCDate;
/** @override */
goog.date.UtcDateTime.prototype.getHours =
goog.date.DateTime.prototype.getUTCHours;
/** @override */
goog.date.UtcDateTime.prototype.getMinutes =
goog.date.DateTime.prototype.getUTCMinutes;
/** @override */
goog.date.UtcDateTime.prototype.getSeconds =
goog.date.DateTime.prototype.getUTCSeconds;
/** @override */
goog.date.UtcDateTime.prototype.getMilliseconds =
goog.date.DateTime.prototype.getUTCMilliseconds;
/** @override */
goog.date.UtcDateTime.prototype.getDay =
goog.date.DateTime.prototype.getUTCDay;
/** @override */
goog.date.UtcDateTime.prototype.setFullYear =
goog.date.DateTime.prototype.setUTCFullYear;
/** @override */
goog.date.UtcDateTime.prototype.setMonth =
goog.date.DateTime.prototype.setUTCMonth;
/** @override */
goog.date.UtcDateTime.prototype.setDate =
goog.date.DateTime.prototype.setUTCDate;
/** @override */
goog.date.UtcDateTime.prototype.setHours =
goog.date.DateTime.prototype.setUTCHours;
/** @override */
goog.date.UtcDateTime.prototype.setMinutes =
goog.date.DateTime.prototype.setUTCMinutes;
/** @override */
goog.date.UtcDateTime.prototype.setSeconds =
goog.date.DateTime.prototype.setUTCSeconds;
/** @override */
goog.date.UtcDateTime.prototype.setMilliseconds =
goog.date.DateTime.prototype.setUTCMilliseconds;
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<!--
Copyright 2009 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
Closure Unit Tests - goog.date.UtcDateTime
</title>
<script src="../base.js">
</script>
<script>
goog.require('goog.date.UtcDateTimeTest');
</script>
</head>
<body>
</body>
</html>
@@ -0,0 +1,127 @@
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.date.UtcDateTimeTest');
goog.setTestOnly('goog.date.UtcDateTimeTest');
goog.require('goog.date.Interval');
goog.require('goog.date.UtcDateTime');
goog.require('goog.date.month');
goog.require('goog.date.weekDay');
goog.require('goog.testing.jsunit');
function testConstructor() {
goog.now = function() {
return new Date(2001, 2, 3, 4).getTime();
};
var d = new goog.date.UtcDateTime();
assertTrue('default constructor', d.equals(new Date(goog.now())));
var d = new goog.date.UtcDateTime(2001);
assertTrue('year only', d.equals(new Date(Date.UTC(2001, 0, 1, 0, 0, 0))));
var d = new goog.date.UtcDateTime(2001, 2, 3, 4, 5, 6, 7);
assertTrue('full date/time',
d.equals(new Date(Date.UTC(2001, 2, 3, 4, 5, 6, 7))));
var d = new goog.date.UtcDateTime(new Date(0));
assertTrue('copy constructor',
d.equals(new Date(Date.UTC(1970, 0, 1, 0, 0, 0))));
}
function testClone() {
var d = new goog.date.UtcDateTime(2001, 2, 3, 4, 5, 6, 7);
assertTrue('clone of UtcDateTime', d.equals(d.clone()));
}
function testAdd() {
var date = new goog.date.UtcDateTime(2007, goog.date.month.OCT, 5);
date.add(new goog.date.Interval(-1, 2));
var expected = new goog.date.UtcDateTime(2006, goog.date.month.DEC, 5);
assertTrue('UTC date + years + months', expected.equals(date));
var date = new goog.date.UtcDateTime(2007, goog.date.month.OCT, 1);
date.add(new goog.date.Interval(0, 0, 60));
var expected = new goog.date.UtcDateTime(2007, goog.date.month.NOV, 30);
assertTrue('UTC date + days', expected.equals(date));
var date = new goog.date.UtcDateTime(2007, goog.date.month.OCT, 1);
date.add(new goog.date.Interval(0, 0, 0, 60 * 24 - 12, -30, -30.5));
var expected = new goog.date.UtcDateTime(2007, goog.date.month.NOV, 29,
11, 29, 29, 500);
assertTrue('UTC date + time, daylight saving ignored', expected.equals(date));
}
function testGetYear() {
var date = new goog.date.UtcDateTime(2000, goog.date.month.JAN, 1);
assertEquals('year of 2000-01-01 00:00:00', 2000, date.getYear());
var date = new goog.date.UtcDateTime(1999, goog.date.month.DEC, 31, 23, 59);
assertEquals('year of 1999-12-31 23:59:00', 1999, date.getYear());
}
function testGetDay() {
var date = new goog.date.UtcDateTime(2000, goog.date.month.JAN, 1);
assertEquals('2000-01-01 00:00:00 is Saturday (UTC + ISO)',
goog.date.weekDay.SAT, date.getUTCIsoWeekday());
assertEquals('2000-01-01 00:00:00 is Saturday (ISO)',
goog.date.weekDay.SAT, date.getIsoWeekday());
assertEquals('2000-01-01 00:00:00 is Saturday (UTC)',
6, date.getUTCDay());
assertEquals('2000-01-01 00:00:00 is Saturday',
6, date.getDay());
var date = new goog.date.UtcDateTime(2000, goog.date.month.JAN, 1, 23, 59);
assertEquals('2000-01-01 23:59:00 is Saturday (UTC + ISO)',
goog.date.weekDay.SAT, date.getUTCIsoWeekday());
assertEquals('2000-01-01 23:59:00 is Saturday (ISO)',
goog.date.weekDay.SAT, date.getIsoWeekday());
assertEquals('2000-01-01 23:59:00 is Saturday (UTC)',
6, date.getUTCDay());
assertEquals('2000-01-01 23:59:00 is Saturday',
6, date.getDay());
}
function testFromIsoString() {
var dateString = '2000-01-02';
var date = goog.date.UtcDateTime.fromIsoString(dateString);
var exp = new goog.date.UtcDateTime(2000, goog.date.month.JAN, 2);
assertTrue('parsed ISO date', exp.equals(date));
var dateTimeString = '2000-01-02 03:04:05';
var dateTime = goog.date.UtcDateTime.fromIsoString(dateTimeString);
var exp = new goog.date.UtcDateTime(2000, goog.date.month.JAN, 2, 3, 4, 5);
assertTrue('parsed ISO date/time', exp.equals(dateTime));
}
function testToIsoString() {
var date = new goog.date.UtcDateTime(2000, goog.date.month.JAN, 2, 3, 4, 5);
assertEquals('serialize date/time',
'2000-01-02 03:04:05', date.toIsoString(true));
assertEquals('serialize time only',
'03:04:05', date.toIsoTimeString(true));
assertEquals('serialize date/time to XML',
'2000-01-02T03:04:05', date.toXmlDateTime());
}
function testIsMidnight() {
assertTrue(new goog.date.UtcDateTime(2000, 0, 1).isMidnight());
assertFalse(new goog.date.UtcDateTime(2000, 0, 1, 0, 0, 0, 1).isMidnight());
}
function testFromTimestamp() {
assertEquals(0, goog.date.UtcDateTime.fromTimestamp(0).getTime());
assertEquals(1234, goog.date.UtcDateTime.fromTimestamp(1234).getTime());
}