Skip to content

Instantly share code, notes, and snippets.

@hongymagic
Created August 18, 2013 01:51
Show Gist options
  • Save hongymagic/6259550 to your computer and use it in GitHub Desktop.
Save hongymagic/6259550 to your computer and use it in GitHub Desktop.
Working with Dates in Backbone.Model
<!DOCTYPE html>
<html>
<head>
<script src="http://documentcloud.github.io/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.io/backbone/backbone-min.js"></script>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<script src="http://marionettejs.com/downloads/backbone.marionette.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
</body>
</html>
// Date rules
// 1. All dates are communicated in UTC format
var Entry = Backbone.Model.extend({
defaults: {
date: undefined,
worked: false
},
initialize: function () {
var date = this.attributes.date;
switch (typeof date) {
case 'object':
break;
case 'string':
date = new Date(date);
break;
default:
break;
}
if (Object.prototype.toString.call(date) !== '[object Date]' || isNaN(date.getTime())) {
throw new Entry.InvalidDateException(this.attributes.date);
}
this.set('date', date);
},
local_date: function () {
return this.get('date').toLocaleDateString();
},
timestamp: function () {
return this.get('date').toLocaleString();
}
}, {
InvalidDateException: function (value) {
this.value = value;
this.message = 'Provided date is invalid';
this.toString = function () {
return this.message + ': "' + this.value + '" (type: ' + Object.prototype.toString.call(value) + '). Date supplied must be a Date object or in UTC format.';
};
}
});
// TEST
function test_date (data) {
try {
var entry = new Entry(data);
console.log(entry, entry.get('date') instanceof Date, entry.local_date(), entry.timestamp());
} catch (e) {
console.error(e, e.toString());
}
}
test_date({ date: new Date() });
test_date({ date: 'Sun, 8 Aug 2013 00:00:00 GMT' });
test_date({});
test_date({ date: '' });
test_date({ date: 1 });
test_date({ date: true });
test_date({ date: '8 Aug 2013 01:25:07 AEST' });
test_date({ date: '8 Aug 2013' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment