Tuesday, 27 July 2021

Javascript new Date(), getTime()

 Javascript new Date() returns date time for current browser time.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

// If browser is in PST 

var test = new Date();

// Tue Jul 27 2021 13:00:24 GMT-0700 (Pacific Daylight Time)


// getTime() returns the UTC timestamp in milseconds(Usually UTC timestamp should be seconds), but JS works with milli seconds. for the given time

var time = test.getTime();

// 1627416024744




Javascript new Date() can also takes parameter such as time string with time zone, new Date('2021-07-26T17:27:35-07:00'), or utc timestamp in mili seconds, it will return the supplied time at browser time zone if no time zone specified. If time zone specified, it will return that time.


Time zone specified

new Date('2021-07-26T17:27:35-07:00')

// Mon Jul 26 2021 17:27:35 GMT-0700 (Pacific Daylight Time)


Time zone not specified with browser at PST 

new Date('July 27 2021')

Tue Jul 27 2021 00:00:00 GMT-0700 (Pacific Daylight Time)


Time zone not specified with browser at PST 

new Date(1627416024744)

Tue Jul 27 2021 13:00:24 GMT-0700 (Pacific Daylight Time)

No comments:

Post a Comment