-2

How to convert a "DD-MMM-YYYY" string to a date in Jquery?

I've a date in string "14-Jun-2014". I want to convert it to a date; something like this 14-06-2014. For $("#InvoiceToDate").text(); I get this "14-Jun-2014"

So for

new Date($("#InvoiceToDate").text()) 

But its showing

Sat Jun 14 2014 00:00:00 GMT+0600 (Bangladesh Standard Time)

I've also tried this

new Date($("#InvoiceToDate").text()).toLocaleString('en-GB');

Now its showing almost what I wanted.

"06/08/2014 00:00:00"

How can I get only dd/MM/yyyy. Please help.

Mahib
  • 3,977
  • 5
  • 53
  • 62
  • I've tried this >> new Date($("#InvoiceToDate").text()) But its showing >> Sat Jun 14 2014 00:00:00 GMT+0600 (Bangladesh Standard Time) – Mahib Jun 13 '14 at 13:28
  • 1
    try like this: http://stackoverflow.com/questions/23532270/date-format-conversion-from-dd-mmm-yyyy-to-dd-mm-yyyy-in-javascript – Uday Jun 13 '14 at 13:32

2 Answers2

4

Something like this:

var fecha = "14-Jun-2014";
var myDate = new Date(fecha);
console.log(myDate);

Fiddle: http://jsfiddle.net/robertrozas/pS8tc/1/

Hackerman
  • 12,139
  • 2
  • 34
  • 45
  • 1
    This will not work in all browsers. [Date() requires](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) a properly formatted date string, which "14-Jun-2014" isn't. – thykka Jun 13 '14 at 13:29
  • 1
    It works with Chrome, but not with Firefox. They have different implementations of Date.parse() – thykka Jun 13 '14 at 13:35
4

I had similar kind of problem. This works for me.

var now = new Date("14-Jun-2014");
now.toLocaleDateString("en-GB");

This returns "14/06/2014" in Chrome.

UPDATE:

FF and IE wouldn't swallow "14-Jun-2014". However, if you could remove the dashes from the string and replace with spaces like "14 Jun 2014" then it will work on both browsers.

var now = new Date("14 Jun 2014");
now.toLocaleDateString("en-GB");

See if this helps.

Siddik
  • 118
  • 1
  • 7