UTC Date Experiment

When working with a UTC date coming from your server you might not want it affected by the client's local timezone settings.

by ecropolis

HTML

<script src="http://stevenlevithan.com/assets/misc/date.format.js"></script>
<script src="http://ideaflyer.s3.amazonaws.com/dhtmlx/dhtmlx.js"></script>
<h1>Working with UTC timestamps</h1>
<ul id="out"></ul>


<p>Change the timezone on your system and you'll better understand how these functions work.</p>

<p class="footnote">Loaded <a href="http://blog.stevenlevithan.com/archives/date-time-format" target="_blank">http://blog.stevenlevithan.com/archives/date-time-format</a> to do a final date format.</p>

CSS

html { font-family: arial, helvetica, verdana; font-size: 90%; }
h1 { font-size: 1.2em }
p { margin-top: 36px; font-weight: bold; }
p.footnote { font-size: .8em }

JavaScript

ts = 1425145585936; /* testing timestamp */
fmt = "m/d/yyyy";
dateFormatter = new dhtmlXCalendarObject("");
formatDate = function (date,format) {
    return dateFormatter.getFormatedDate(format, date);
};
millisecondToDate = function (ms) { //returns a date obj from a timestamp
    return new Date(Number(ms)); 
};

freezeUTCDate = function(ms){ //returns a new date object using chopped up components of UTC date object without having it offset by local time settings.
     var d = millisecondToDate(ms);
     return new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds()); 
}

$(document).ready(function(){
    $out = $('#out');
    $out.append( '<li><strong>UTC datestamp: </strong>' + millisecondToDate(ts).toUTCString() +'</li>' );
    $out.append( '<li><strong>localized date: </strong>' + millisecondToDate(ts).toString() +'</li>');
    $out.append( '<li><strong>Freeze UTC date: </strong>' + freezeUTCDate(ts).toString() +'</li>' );
    $out.append( '<li><strong>Formatted: </strong>' + freezeUTCDate(millisecondToDate(ts)).format(fmt) +'</li>' ); //format using http://blog.stevenlevithan.com/archives/date-time-format (see external resources)

 $out.append( '<li><strong>Formatted with DHTMLx: </strong>' + formatDate(freezeUTCDate(millisecondToDate(ts)),"%m/%d/%Y") +'</li>' ); 
             //format using DHTMLx)
});