JackDev
JackDev

Reputation: 5062

How do I get the current date in Javascript, using an argument

There are loads of questions about the current date in JavaScript in general, but in my scenario, I have to pass in something to the date object, because usually there is a valid date I'm looking for. However, my question is - assuming the argument is undefined, what should I pass to mimic new Date()?

As an example, my code will do something like this.

const date = '2019-11-26T19:10:12.000Z'
const diff = new Date(date).getTime() - new Date().getTime()

While my components are rendering, I need to give date an initial value (while it loads from the server). During this initial loading time, I expect the diff to equal 0.

I have tried the following

new Date(undefined) >> Invalid Date

new Date('') >> Invalid Date

new Date(null) >> Thu Jan 01 1970

new Date(0) >> Thu Jan 01 1970

I'm trying to solve it in a simple way, by passing in whatever value would match no argument for Date. It seems weird, but if it's the case, I'll just assume it's JavaScript date objects being weird.

Upvotes: 0

Views: 162

Answers (1)

R3tep
R3tep

Reputation: 12874

You can define your date with another date object as parameter.

var params = new Date;
var date = new Date(params);

console.log(date)

Upvotes: 2

Related Questions