0

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);
3
  • Either you have a date object, or you have the string "10/04/2016", you can't have both at the same time (but you could have both in different variables) Commented Oct 4, 2016 at 15:39
  • what research have you done and what have you tried? Using keywords from in this question in a search engine will produce many many results Commented Oct 4, 2016 at 15:44
  • Just parse the string and create the date object yourself. Commented Oct 4, 2016 at 15:45

5 Answers 5

2

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.

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

6 Comments

Really, your browser outputs that format when for date objects? Mine would output UTC dates, as in 2016-10-04T09:28:00.000Z etc ?
Yes! minus the GMT part: console.log(new Date().toString()); prints Tue Oct 04 2016 10:36:13 GMT-0600 in my browser.
That's still not even close to October 04, 2016 9:28 AM
Sorry, I saw it similar at first look, but you are right it is different. I'll update my answer.
"First, convert that String date into a Date object using the Date constructor:" is not a good idea. Parsing of the OP date format is entirely implementation dependent and may return the correct date, the wrong date or an invalid date.
|
2

Use an array of months to get the numerical value, and then just parse it however you'd like

var months = [
	"January",
	"February",
	"March",
	"April",
 	"May",
 	"June",
	"July",
 	"August",
 	"September",
	"October",
	"November",
	"December"
];

function pad(n) { return n<10?'0'+n:n }

var PublishDate = {
	value : "October 04, 2016 9:28 AM"
}

var parts = PublishDate.value.split(/[\s\,\:]+/);
var year  = +parts[2];
var month = months.indexOf(parts[0]);
var day   = +parts[1];

var date  = new Date(year, month, day);                  // date object
var str   = pad(month+1) + '/' + pad(day) + '/' +  year; // the string "10/04/2016"

console.log(date);
console.log(str);
.as-console-wrapper {top : 0}

2 Comments

wow there is actually a much easier way ^^ new Date("October 04, 2016 9:28 AM") works fine ^^
@SteevePitis - good for you, but it's not a valid ISO 8601 date, so wether or not the engine is able to parse it, would be implementation dependant, and not guaranteed at all.
1

// Example PublishDate result
var PublishDate = {
  value: 'October 04, 2016 9:28 AM'
};

// convert "date string" into "date object"
var date = new Date(PublishDate.value);

// build required "date string"
var dateShort = (date.getMonth() +1) + '/'
  + date.getDate() + '/'
  + date.getFullYear();

// console log to show result
console.log(dateShort);

1 Comment

Need to add a + 1 to the date.getMonth() part, since that method returns a zero based month number so it is printing 10/4/2016 instead of 9/04/2016
1

Parsing a string like "October 04, 2016 9:28 AM" using the Date constructor is entirely implementation dependent and may result in an incorrect date or invalid date, so either use a parser (there are many good ones available) or write a small function yourself to parse the string.

But if you just want to reformat it, then parsing to a Date isn't required at all, just reformat the string. E.g.

/* Reformat a string like October 04, 2016 9:28 AM to m/d/y format
** @param {string} s - string in format MMMM DD, YYYY h:mm ap
** @returns {string} reformatted date in MM/DD/YYYY format
*/
function reformatDate(s) {
  var months = {jan:'01',feb:'02',mar:'03',apr:'04', may:'05',jun:'06',
                jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
  var b = s.match(/\w+/g) || [];
  return months[b[0].toLowerCase().substr(0,3)] + '/' + b[1] + '/' + b[2];
}

console.log(reformatDate('October 04, 2016 9:28 AM'));
                

Comments

0

There is a lot of question like this on SO ... Try to search a little next time.

var date = new Date(PublishDate.value);
console.log((date.getDate() + '/' + (date.getMonth() + 1) + '/' +  date.getFullYear());

1 Comment

Parsing of the OP date format is entirely implementation dependent and may return the correct date, the wrong date or an invalid date. Either write a simple function or use one of the many parsers available.

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.