Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spit up date after converting it to a string

Tags:

javascript

I have a date in milliseconds that I convert to a readable date. Then I covert it to a string so I can split it up and break it down to use the parts I need. The problem is when I break it down by space, it breaks down each character by itself and does not split it up where there's a space. Can anybody explain why and what I'm doing wrong?

here's my code:

var formattedDate = new Date(somedateMS);

var formattedDateSplit = formattedDate.toString();

formattedDateSplit.split(" ");

console.log(formattedDateSplit);  // Mon May 18 2015 18:35:27 GMT-0400 (Eastern Daylight Time)
console.log(formattedDateSplit[0]); // M
console.log(formattedDateSplit[1]); // o
console.log(formattedDateSplit[2]); // n
console.log(formattedDateSplit[3]); // [space]
console.log(formattedDateSplit[4]); // M
console.log(formattedDateSplit[5]); // a
console.log(formattedDateSplit[6]); // y

How can I split it up so I can get rid of the day of the week, and just have the May 18 2015 18:35:27 into 4 separate values? (May, 18, 2015, 18:35:27)?

I've done this before and not sure why this time it's splitting it up by character.

Thank you!

like image 721
SS113 Avatar asked Mar 17 '23 00:03

SS113


1 Answers

You're setting formattedDateSplit to the whole Date string, unsplit:

var formattedDateSplit = formattedDate.toString();

Then you do this, which is probably a typo:

formattedSplit.split(" ");

since that's the wrong variable name; what you probably meant was:

formattedDateSplit = formattedDateSplit.split(" ");

You're getting individual characters because the subsequent code is just indexing into the string itself, not the split-up version of the string. The .split() function returns the array, so you have to assign it to something; it does not modify the string.

like image 83
Pointy Avatar answered Mar 24 '23 20:03

Pointy