Skip to content

Instantly share code, notes, and snippets.

@olly
Created November 4, 2010 21:59
Show Gist options
  • Save olly/663286 to your computer and use it in GitHub Desktop.
Save olly/663286 to your computer and use it in GitHub Desktop.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JSON Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
Date.ISO8601Matcher = /([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?/;
Date.prototype.setISO8601 = function (string) {
var d = string.match(Date.ISO8601Matcher);
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
var stringMatchingDateReplacer = function(key, value) {
if(typeof value === 'string' && value.match(Date.ISO8601Matcher)) {
var date = new Date();
date.setISO8601(value);
return date;
}
return value;
}
var keyMatchingDateReplacer = function(key, value) {
var dateKeys = ['date'];
if(dateKeys.indexOf(key) > -1) {
var date = new Date();
date.setISO8601(value);
return date;
}
return value;
}
$(document).ready(function() {
// JSON
data = {date: new Date()};
json = JSON.stringify(data)
$('#json').text(json);
// String Matching
var stringMatchingData = JSON.parse(json, stringMatchingDateReplacer);
$('#stringMatchingDateType').text(typeof stringMatchingData.date);
$('#stringMatchingDate').text(stringMatchingData.date.toString());
// Key Matching
var keyMatchingData = JSON.parse(json, keyMatchingDateReplacer);
$('#keyMatchingDateType').text(typeof keyMatchingData.date);
$('#keyMatchingDate').text(keyMatchingData.date.toString());
});
</script>
</head>
<body>
<h5>JSON</h5>
<pre id="json"></pre>
<h5>String Matching</h5>
<pre id="stringMatchingDateType"></pre>
<pre id="stringMatchingDate"></pre>
<h5>Key Matching</h5>
<pre id="keyMatchingDateType"></pre>
<pre id="keyMatchingDate"></pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment