Home > Mobile >  js date separator gives different answers when using getDate()
js date separator gives different answers when using getDate()

Time:08-13

In the code below, why do we get different answers with getDate()

 temp = new Date("2022-05-15")
 temp1 = new Date('2022/05/15')

console.log(temp.getDate())
console.log(temp1.getDate())

CodePudding user response:

The ECMAScript standard defines certain date/time strings that are parsed in a standard way: https://tc39.es/ecma262/#sec-date-time-string-format

Any other values the client chooses to accept may be implementation specific. Mozilla documents some common behaviors here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#fall-back_to_implementation-specific_date_formats

If you specifically intend to support yyyy/mm/dd in a cross-client compatible way, you may want to parse it yourself and supply the values to the new Date(year, month, day) (noting that month is 0-indexed "off by one")

const [yyyy,mm,dd] = '2022/05/15'.match(/(\d{4})\/(\d )\/(\d )/).slice(1).map(e => parseInt(e));
new Date(yyyy, mm - 1, dd)

or simply new Date('2022/05/15'.replace(/\//g, '-'))

CodePudding user response:

In different parts of the world, date is described in different ways.

  1. Date according to the ISO is, yyyy-mm-dd
  2. Date according to some countries like USA is, mm/dd/yyyy
  3. Date according to most other countries is, dd/mm/yyyy

Most Javascript implementations support the first two formats. Its said that some browser implementations of javascript try to guess if the third format is used and adapt.

To be on the safer side, go with the ISO format (yyyy-mm-dd). Or if you have trouble remembering which separator is used by ISO, you can skip the string and enter the date elements as comma separated values.

temp = new Date(2022, 5, 15)
console.log(temp.getDate())

This page has info on which format works and which doesn't (https://www.w3schools.com/js/js_date_formats.asp).

  • Related