5

In JavaScript, Result of the Date Object is different when it comes to Different Time Zones and Different Notation.

eg.

var res= "2018-08"; 
var dat=new Date(res);  

Result are :

Tue Jul 31 2018 22:00:00 GMT-0200 (West Greenland Summer Time)  for GMT-0200  Time Zone 

and

 Wed Aug 01  2018 05:30:00 GMT+0530 (India Standard Time)

But When

var res= "2018/08"; 

We are getting same date

Wed Aug 01 2018 00:00:00 GMT+0530 (India Standard Time)

Wed Aug 01 2018 00:00:00 GMT-0300 (Atlantic Daylight Time)

Can Anyone Explain me Why its not Constant when we gave "-" as delimiter

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32

1 Answers1

1

In order for the object to understand the format you're feeding it, is by actually telling it the format you're feeding it.

The below might help you achieve what you're after:

Option 1:

Using date set methods or using the Date.parse() functionality (if that satisfies your needs).

Option 2:

Using something ott similar to momentjs that will do the logic for you.

Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34
  • Yeah.It helps me to learn Date Object Behaviour.But,My Question is Why the date will change when I use "-" as delimiter and why not change of date won't happen when I use "/" as delimiter.. – murari setty gnana vinay Aug 22 '18 at 17:08
  • Because changing the character changes the locale. - Meaning, that for instance India might use 'mm-dd-yyyy' and US might use 'dd/mm/yyyy', and this is handled inside JavaScript. - You can read more [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#Examples). – Julian Camilleri Aug 23 '18 at 08:41