Search code examples
javascriptnode.jsdatevisual-studio-codevscode-code-runner

VSCode Javascript - get exact local new Date() value


Currently the time on my machine is 07:55

If I console.log(new Date()) in my vscode terminal then I get the wrong time of 05:55. This is because my time zone (South Africa) is +2. So in vscode / node my new Date() is showing the universal time, not my local time.

If I console.log(new Date()) in a .html file (if I run it in Chrome) then I get the correct time of 07:55.

Is the problem in node, vscode or somewhere else? And how can I fix this problem so that my vscode/node console.log's the correct time.

console.log(new Date().getHours()) does indeed give me the correct hour of 7, but I don't understand why console.log(new Date()) gives me the wrong hour of 2019-09-11T05:55:00.480Z

console.log(new Date().toLocaleString()) does indeed give me the correct time, but I don't want that format. I just want the basic new Date() format for database purposes.

// 2019-09-11T05:55:00.480Z
console.log(new Date())    

// 9/11/2019, 7:55:00 AM
console.log(new Date().toLocaleString())

Solution

  • You can do new Date().toString() in node to get the format from chrome

    node:

    console.log(new Date()); // 2019-09-11T06:25:01.665Z
    console.log(new Date().toLocaleString()); // 9/11/2019, 1:25:01 PM
    console.log(new Date().toString()); // Wed Sep 11 2019 13:25:01 GMT+0700 (GMT+07:00)