1

I am updated the value of an HTML input field with data from a query:

$("##warranty_end_date#id#").val(warranty_end_date);

But the data is store in my database as a SQL Date/Time and has an output like this: May, 08 2019 00:00:00 -0400

I would like the data to be formatted like this: 05/08/2016

How can I accomplish this?

Brian Fleishman
  • 1,237
  • 3
  • 21
  • 43
  • 3
    Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – godzillante Dec 23 '16 at 14:46

4 Answers4

1

Maybe you could format the date in the SQL query already. Something like:

SELECT convert(varchar, getdate(), 101)  

101 = mm/dd/yyyy – 10/02/2008

Wouter den Ouden
  • 1,523
  • 2
  • 17
  • 44
  • Unfortunately I am returning a bunch of columns in my query so I cannot do it that way. Does jquery have a simple mask function? – Brian Fleishman Dec 23 '16 at 14:53
  • I agree this solution would be good to use, but this is not what the OP asked for. I don't understand why this solution is getting up votes. – Pegues Dec 23 '16 at 15:15
1

warranty_end_date = "May, 08 2019 00:00:00 -0400";

var d = new Date(warranty_end_date);

var f = ("00" + (d.getDate()).toString()).slice(-2) + "/" + ("00" + (d.getMonth()+1).toString()).slice(-2) + "/" + (1900 + d.getYear()).toString();

$("##warranty_end_date#id#").val(f);

Falco
  • 1,458
  • 3
  • 19
  • 47
  • I actually realized that this is outputting dd/mm/yyyy . How can I switch it to mm/dd/yyyy? – Brian Fleishman Dec 23 '16 at 18:36
  • 1
    just switch the part in the middle with the part in beginning: var f = ("00" + (d.getMonth()+1).toString()).slice(-2) + "/" + ("00" + (d.getDate()).toString()).slice(-2) + "/" + (1900 + d.getYear()).toString(); – Falco Dec 25 '16 at 12:37
0
var date = new Date('2010-10-11T00:00:00+05:30');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());
Balaji Marimuthu
  • 1,940
  • 13
  • 13
  • Please consider elaborating a little instead of posting plain code. The objective here is to educate, not spoon-feed. – ShahiM Dec 23 '16 at 17:03
0

You can accomplish this using the following:

var date = new Date('May, 08 2019 00:00:00 -0400');
var output = date.toLocaleFormat('%m/%d/%Y');
alert(output);

Here's a jsfiddle: https://jsfiddle.net/y4zemzqg/

Also, look over using moment.js. http://momentjs.com/ Moment.js makes formatting dates and time incredibly easy. I've used it for quite some time with no issue:

var theDate = moment('May, 08 2019 00:00:00 -0400').format('MM/DD/YYYY');
alert(theDate);

Here is a JS Fiddle using the moment.js solution: https://jsfiddle.net/v923bn5s/

Pegues
  • 1,693
  • 2
  • 21
  • 38