From 75a6bbd80a04eb2222cf22e155e272e7f10f64b1 Mon Sep 17 00:00:00 2001 From: Rufus Pollock Date: Sun, 10 Jun 2012 12:35:39 +0100 Subject: [PATCH] [#152,view/timeline][s]: more robust data parsing with tests - fixes #152. * Also discover and fix "bug" re momentjs timezone calculation and toDate. --- src/view.timeline.js | 24 ++++++++++++++++++++---- test/view.timeline.test.js | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/view.timeline.js b/src/view.timeline.js index c556a1e4..5c0da584 100644 --- a/src/view.timeline.js +++ b/src/view.timeline.js @@ -79,12 +79,11 @@ my.Timeline = Backbone.View.extend({ } }; this.model.currentRecords.each(function(doc) { - var start = doc.get(self.state.get('startField')); + var start = self._parseDate(doc.get(self.state.get('startField'))); + var end = self._parseDate(doc.get(self.state.get('endField'))); if (start) { - var end = doc.get(self.state.get('endField')); - end = end ? moment(end).toDate() : null; var tlEntry = { - "startDate": moment(start).toDate(), + "startDate": start, "endDate": end, "headline": String(doc.get('title') || ''), "text": doc.summary() @@ -103,6 +102,23 @@ my.Timeline = Backbone.View.extend({ return out; }, + _parseDate: function(date) { + var out = date.trim(); + out = out.replace(/(\d)th/g, '$1'); + out = out.replace(/(\d)st/g, '$1'); + out = out.trim() ? moment(out) : null; + if (out.toDate() == 'Invalid Date') { + return null; + } else { + // fix for moment weirdness around date parsing and time zones + // moment('1914-08-01').toDate() => 1914-08-01 00:00 +01:00 + // which in iso format (with 0 time offset) is 31 July 1914 23:00 + // meanwhile native new Date('1914-08-01') => 1914-08-01 01:00 +01:00 + out = out.subtract('minutes', out.zone()); + return out.toDate(); + } + }, + _setupTemporalField: function() { this.state.set({ startField: this._checkField(this.startFieldNames), diff --git a/test/view.timeline.test.js b/test/view.timeline.test.js index 583afc79..8746b0bb 100644 --- a/test/view.timeline.test.js +++ b/test/view.timeline.test.js @@ -48,3 +48,23 @@ test('render etc', function () { view.remove(); }); +test('_parseDate', function () { + var dataset = Fixture.getDataset(); + var view = new recline.View.Timeline({ + model: dataset + }); + var testData = [ + [ '1st August 1914', '1914-08-01T00:00:00.000Z' ], + [ '1 August 1914', '1914-08-01T00:00:00.000Z' ], + [ 'August 1st 1914', '1914-08-01T00:00:00.000Z' ], + [ '1914-08-01', '1914-08-01T00:00:00.000Z' ], + [ '1914-08-01T08:00', '1914-08-01T08:00:00.000Z' ], + [ 'afdaf afdaf', null ] + ]; + _.each(testData, function(item) { + var out = view._parseDate(item[0]); + if (out) out = out.toISOString(); + equal(out, item[1]); + }); +}); +