5

I have a string looking like so:

"2013/1/16"

Is there any way I could quickly convert it into date object in javascript, something like:

convertToDateTime("2013/1/16", "yyyy/MM/dd")
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Bartosz
  • 4,542
  • 11
  • 43
  • 69

2 Answers2

24

It's pretty simple:

var myDate = new Date("2013/1/16");

That should do the trick.
Have a look at the documentation for the Date object

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • i do `new Date("12-01-2019")` and it gives me `Sun Dec 01 2019 00:00:00 GMT+0530 (India Standard Time)` . what if i want the date object to be the 12th Jan and not 1st December – Abhi Feb 12 '19 at 08:44
  • @Abhi Use substr function to change the date to 2019-01-12 and add "T00:00:00" to it, to make it look like: "2019-01-12T00:00:00" This way, Date object knows it is a date in ISO format and it correctly detects month and day. – Arash HF Jul 04 '19 at 08:05
  • Time zones can present a confusing (and I hope I don't make it worse here). yada = new Date("2013/1/16") returns an object representing 12AM in the time zone of the machine on which that code is run, in my case Wed Jan 16 2013 00:00:00 GMT-0800 (Pacific Standard Time) yada.getUTCHours() retuns 8 - the corresponding time in London. 8 – captain puget Dec 26 '21 at 01:06
-1

var myDate = new Date("2013/1/16");

var str = "2013/1/16"; var strToDate = new Date(str);