1

Is it possible to enter date in dd/mm/yyyy format into newDate (e.g. 03/01/2018) so that it returns object Wed Jan 03 2018 00:00:00 GMT+0000 (Greenwich Mean Time) {}?

If I have a date 03/01/2018 it returns Thu Mar 01 2018 00:00:00 GMT+0000 (Greenwich Mean Time) {} instead... I'm not trying to pass mm/dd/yyyy format..

I've looked at plenty of posts on this and can't find an answer to my question.

LazioTibijczyk
  • 1,701
  • 21
  • 48

3 Answers3

4

You have no control over the Date constructor, so you need to feed it a date in the format that it wants. Since you are formatting the date yourself, it is better to use the other Date constructor, which takes the year, monthIndex, and day as arguments, since it is more bullet-proof across different browsers and runtimes:

  function my_date(date_string) {
      var date_components = date_string.split("/");
      var day = date_components[0];
      var month = date_components[1];
      var year = date_components[2];
      return new Date(year, month - 1, day);
    }
    
    console.log(my_date("03/01/2018"));

The case of dates one area where I install the moment library on nearly every JavaScript project I create.

Note: Snippet may display the result differently; check your console.

ouni
  • 3,233
  • 3
  • 15
  • 21
0

You could use regex like so:

var date = new Date("03-01-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
Prock
  • 410
  • 1
  • 5
  • 20
  • It's not a good idea to parse a string to make another string that must be parsed again. After the first parse, you can pass the parts directly to the Date constructor. – RobG Jun 29 '18 at 02:50
0

I suggest you use momentjs from http://momentjs.com/ . it is very easy to use to output any format u want.

moment().format('MMMM Do YYYY, h:mm:ss a'); // June 28th 2018, 10:30:09 pm
moment().format('dddd');                    // Thursday
moment().format("MMM Do YY");               // Jun 28th 18
moment().format('YYYY [escaped] YYYY');     // 2018 escaped 2018
moment().format();                         
Zi Gang
  • 193
  • 1
  • 1
  • 18