1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 var timeutil = (function() {
9 * Offset needed to convert event times to Date objects.
10 * Updated whenever constants are loaded.
12 var timeTickOffset = 0;
15 * Sets the offset used to convert tick counts to dates.
17 function setTimeTickOffset(offset) {
18 // Note that the subtraction by 0 is to cast to a number (probably a float
19 // since the numbers are big).
20 timeTickOffset = offset - 0;
24 * The browser gives us times in terms of "time ticks" in milliseconds.
25 * This function converts the tick count to a Javascript "time", which is
26 * the UTC time in milliseconds.
28 * @param {string} timeTicks A time represented in "time ticks".
29 * @return {number} The Javascript time that |timeTicks| represents.
31 function convertTimeTicksToTime(timeTicks) {
32 return timeTickOffset + (timeTicks - 0);
36 * The browser gives us times in terms of "time ticks" in milliseconds.
37 * This function converts the tick count to a Date() object.
39 * @param {string} timeTicks A time represented in "time ticks".
40 * @return {Date} The time that |timeTicks| represents.
42 function convertTimeTicksToDate(timeTicks) {
43 return new Date(convertTimeTicksToTime(timeTicks));
47 * Returns the current time.
49 * @return {number} Milliseconds since the Unix epoch.
51 function getCurrentTime() {
56 * Adds an HTML representation of |date| to |parentNode|.
58 * @param {DomNode} parentNode The node that will contain the new node.
59 * @param {Date} date The date to be displayed.
60 * @return {DomNode} The new node containing the date/time.
62 function addNodeWithDate(parentNode, date) {
63 var span = addNodeWithText(parentNode, 'span', dateToString(date));
64 span.title = 't=' + date.getTime();
69 * Returns a string representation of |date|.
71 * @param {Date} date The date to be represented.
72 * @return {string} A string representation of |date|.
74 function dateToString(date) {
75 var dateStr = date.getFullYear() + '-' +
76 zeroPad_(date.getMonth() + 1, 2) + '-' +
77 zeroPad_(date.getDate(), 2);
79 var timeStr = zeroPad_(date.getHours(), 2) + ':' +
80 zeroPad_(date.getMinutes(), 2) + ':' +
81 zeroPad_(date.getSeconds(), 2) + '.' +
82 zeroPad_(date.getMilliseconds(), 3);
84 return dateStr + ' ' + timeStr;
88 * Prefixes enough zeros to |num| so that it has length |len|.
89 * @param {number} num The number to be padded.
90 * @param {number} len The desired length of the returned string.
91 * @return {string} The zero-padded representation of |num|.
93 function zeroPad_(num, len) {
95 while (str.length < len)
101 setTimeTickOffset: setTimeTickOffset,
102 convertTimeTicksToTime: convertTimeTicksToTime,
103 convertTimeTicksToDate: convertTimeTicksToDate,
104 getCurrentTime: getCurrentTime,
105 addNodeWithDate: addNodeWithDate,
106 dateToString: dateToString