Smithmi8 Smithmi8 - 2 months ago 7
Javascript Question

Javascript: convert string with full month to date object

I have a string variable

"PublishDate"
and then when I check the value using
"PublishDate.value"
it returns a string like

"October 04, 2016 9:28 AM"


I need to convert it to a date object that is formatted like
"10/04/2016"


I am not sure how this is done in javascript:

var d = new Date("October 04, 2016 9:28 AM");
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var hours = d.getHours();
var min = d.getMinutes(); //10/04/2016
console.log(month+1+'/'+date+'/'+year);

Answer

First, convert that String date into a Date object using the Date constructor:

var d = new Date(PublishDate.value);

EDIT: Always consider the case that your format may not be supported by the browser. In the case of Firefox, the MDN states that it will support certain date formats:

The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

IE's MSDN Javascript reference also says:

It first tries to parse a date string by using the ISO Date Format. If the date string is not in ISO format, JavaScript tries to parse the date by using other Other Date Formats.

Also, consider that the MDN itself discourages parsing String dates using the constructor or Date.parse(), even though it works for your specific case:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

If you need to support other varieties of date formats or a variety of browsers, you can also consider Momtent.js javascript library or do your own parsing with RegEx, like in @RobG's and @adeneo's answers.


Then, you need to extract the parts you want (month, day, year) and concatenate them in a string with the slash as a separator, like in @user3254198's answer or @Steeve Pitis's answer:

d.getDate() + '/' 
    + (d.getMonth() + 1) + '/' 
    +  d.getFullYear()

Remember that the PublishDate.value.getMonth() method returns a zero-based month numerical representation of the month, so if you want a 1-12 value, add a +1 to it.

Feel free to ask any further! Good luck.