1

When I apply the following code new Date("25-06-2019") in javascript, it always gives invalid date. But the same format is working in PHP.

What can be the reason of this? not valid format for javascript?

Manoj Thakur
  • 111
  • 1
  • 4
  • 2
    Because Date objects in JS and PHP are nothing alike? [Check the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) for why that is an invalid date. In short, it's neither ISO 8601 compliant, nor RFC 2822 compliant. You've essentially given `Date` a random collection of symbols. – VLAZ Jun 25 '19 at 06:19
  • To know more about date and time you can check this https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date/34015511#34015511 – Robin Jun 25 '19 at 06:31
  • @Robin that's for formatting the content of a Date, not for constructing Dates. – VLAZ Jun 25 '19 at 06:33

2 Answers2

2

You need to use either an ISO 8601 date, or an RFC 2822 date. See (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).

If you're doing something more sophisticated, I'd suggest using Moment.js, it will do a lot of Date parsing / formatting / manipulation for you.

For example:

let iso8601Date = '2019-06-25';
console.log(new Date(iso8601Date));

let rfc2822Date = 'Tue, 25 Jun 2019 +0000'
console.log(new Date(rfc2822Date ));

// Or you can use moment.js which is great for date parsing, formatting, etc.
console.log(new moment.utc("25-06-2019", "DD-MM-YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
1

new Date("25-06-2019") is giving you invalid date because you are passing invalid date string.

There are 4 ways to create a new date object:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)

So your case is 4th one, so valid date string will look like October 13, 2014 11:13:00 If you pass above date string say

console.log(new Date("October 13, 2014 11:13:00"));

It will work fine.

Also, you can provide valid ISO 8601 strings.

console.log(new Date("2008-09-15"));

You can refer http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm for ISO 8601 string formats.

Jaydeep
  • 1,686
  • 1
  • 16
  • 29
  • (a subset of) ISO 8601 strings are also valid. – VLAZ Jun 25 '19 at 06:23
  • That link is not very useful - not every single ISO 8601 variation is supported - [the specs](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) define it in a more concise and more precise way. – VLAZ Jun 25 '19 at 06:32