0

This is the code I currently have but I am struggling to convert it to UTC

var today = Date.UTC(new Date());
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var H = today.getHours();
var i = today.getMinutes();
var s = today.getSeconds();

if(dd<10) {
    dd = '0'+dd
} 

if(mm<10) {
    mm = '0'+mm
} 

today = yyyy + '-' + mm + '-' + dd + ' ' + H + ':' + i + ':' + s;

Any ideas on how I can get this working in the same timestamp format? Thanks!

10

1 Answer 1

1

Date objects are always stored in UTC - the .getXxx() functions you're calling implicitly convert that UTC time into your local timezone.

To extract the relevant fields in UTC time instead you should be using the .getUTCxxx() family of functions.

//
// returns the date and time in format 'YYYY-MM-DD hh:mm:ss'
//
// will take a `Date` object, or use the current system
// time if none is supplied
//
function UTC_DateTime(date) {
    if (date === undefined) {
         date = new Date();
    }

    function pad2(n) {
        return (n < 10) ? ('0' + n) : n;
    }

    return date.getUTCFullYear() + '-' +
           pad2(date.getUTCMonth() + 1) + '-' +
           pad2(date.getUTCDay()) + ' ' +
           pad2(date.getUTCHours()) + ':' +
           pad2(date.getUTCMinutes()) + ':' +
           pad2(date.getUTCSeconds());
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you are a life saver!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.