Skip to content

Commit 2adcdfe

Browse files
committed
Add extended ISO 8601 support.
The d3.time.format.iso is designed to be compatible with the default JSON serialization of dates, which includes milliseconds. So, d3.time.format now supports the %L directive for formatting and parsing milliseconds. This commit also changes d3.time.format.iso to use native ISO date methods, if available.
1 parent 307016e commit 2adcdfe

5 files changed

Lines changed: 64 additions & 11 deletions

File tree

d3.time.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ var d3_time_formats = {
7878
H: function(d) { return d3_time_zfill2(d.getHours()); },
7979
I: function(d) { return d3_time_zfill2(d.getHours() % 12 || 12); },
8080
j: d3_time_dayOfYear,
81+
L: function(d) { return d3_time_zfill3(d.getMilliseconds()); },
8182
m: function(d) { return d3_time_zfill2(d.getMonth() + 1); },
8283
M: function(d) { return d3_time_zfill2(d.getMinutes()); },
8384
p: function(d) { return d.getHours() >= 12 ? "PM" : "AM"; },
@@ -104,6 +105,7 @@ var d3_time_parsers = {
104105
H: d3_time_parseHour24,
105106
I: d3_time_parseHour12,
106107
// j: function(d, s, i) { /*TODO day of year [001,366] */ return i; },
108+
L: d3_time_parseMilliseconds,
107109
m: d3_time_parseMonthNumber,
108110
M: d3_time_parseMinutes,
109111
p: d3_time_parseAmPm,
@@ -277,6 +279,12 @@ function d3_time_parseSeconds(date, string, i) {
277279
return n ? (date.setSeconds(+n[0]), i += n[0].length) : -1;
278280
}
279281

282+
function d3_time_parseMilliseconds(date, string, i) {
283+
d3_time_numberRe.lastIndex = 0;
284+
var n = d3_time_numberRe.exec(string.substring(i, i + 3));
285+
return n ? (date.setMilliseconds(+n[0]), i += n[0].length) : -1;
286+
}
287+
280288
// Note: we don't look at the next directive.
281289
var d3_time_numberRe = /\s*\d+/;
282290

@@ -364,7 +372,19 @@ d3_time_format_utc.prototype = {
364372
setMonth: function(x) { this._.setUTCMonth(x); },
365373
setSeconds: function(x) { this._.setUTCSeconds(x); }
366374
};
367-
d3.time.format.iso = d3.time.format.utc("%Y-%m-%dT%H:%M:%SZ");
375+
var d3_time_formatIso = d3.time.format.utc("%Y-%m-%dT%H:%M:%S.%LZ");
376+
377+
d3.time.format.iso = Date.prototype.toISOString ? d3_time_formatIsoNative : d3_time_formatIso;
378+
379+
function d3_time_formatIsoNative(date) {
380+
return date.toISOString();
381+
}
382+
383+
d3_time_formatIsoNative.parse = function(string) {
384+
return new Date(string);
385+
};
386+
387+
d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
368388
function d3_time_range(floor, step, number) {
369389
return function(t0, t1, dt) {
370390
var time = floor(t0), times = [];

0 commit comments

Comments
 (0)