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?

1

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I actually realized that this is outputting dd/mm/yyyy . How can I switch it to mm/dd/yyyy?
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();
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

2 Comments

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?
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.
0
var date = new Date('2010-10-11T00:00:00+05:30');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

1 Comment

Please consider elaborating a little instead of posting plain code. The objective here is to educate, not spoon-feed.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.