JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<input id="isoDateTime" value="" size="20" style="float:left" /> <button id="isoToDateTime">Go</button><br style="clear:left;"/>
Converted Date Time: <span id="isoToDateTimeTarget"></span>
</div>
JavaScript
var $j = jQuery.noConflict();
var d = new Date();
var isoNow = isoDateTime(d);
$j(function(){
$j('#isoDateTime').val(isoNow);
$j('#isoToDateTime').click(function() {
var iso = $j('#isoDateTime').val();
var dt = isoToDateTime(iso);
$j('#isoToDateTimeTarget').html(dt);
});
});
function isoDateTime(d) {
function pad(n){
return n<10 ? '0'+n : n
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
function isoToDateTime(value) {
var output = '';
if (value != '0001-01-01T00:00:00') {
var d = new Date();
d.setISO8601(value);
//desired output format: 5/17/2011 8:34:56 AM - below does not return local time
output = d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear() + " " + setClockTime(d)
}
return output;
}
function setClockTime(d)
{
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var suffix = "AM";
if (h > 11) {suffix = "PM";}
if (h > 12) {h = h - 12;}
if (h == 0) {h = 12;}
if (h < 10) {h = "0" + h;}
if (m < 10) {m = "0" + m;}
if (s < 10) {s = "0" + s;}
return h + ":" + m + ":" + s + " " + suffix;
}
//convert an ISO8601 date string into a js date object
Date.prototype.setISO8601 = function(dString){
var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
if (dString.toString().match(new RegExp(regexp))) {
var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
if (dString.toString().match(new RegExp(regexp))) {
var d = dString.match(new RegExp(regexp));
var offset = 0;
this.setUTCDate(1);
this.setUTCFullYear(parseInt(d[1],10));
this.setUTCMonth(parseInt(d[3],10) - 1);
...