Brian Miller Posted October 28, 2023 Share Posted October 28, 2023 I've been trying to figure this out but I just can't seem to do it. I'm wondering if someone could help... I've got a variable with a date that looks like this "20240102" (YYYYMMDD) and I'd like a function that would convert this date into "Jan 2, 2024". Can someone help me? Link to comment Share on other sites More sharing options...
0 Brian Miller Posted October 28, 2023 Author Share Posted October 28, 2023 Here is what I've written so far... function dateFormetter(yyyymmdd) { const month = yyyymmdd.substring(4, 6); const day = yyyymmdd.substring(6, 8); const year = yyyymmdd.substring(0, 4); const date = new Date(year, month, day); const nameOfMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; return `${nameOfMonths[date.getMonth()]} ${parseInt(day)}, ${year}`; } It doesn't quite seem to work though Link to comment Share on other sites More sharing options...
0 +DonC Subscriber² Posted October 28, 2023 Subscriber² Share Posted October 28, 2023 Date handling in JavaScript is quite limited. If you're doing date handling, I'd recommend using a library instead. The one I tend to use is moment.js. However, there's not much point involving Date objects in your code though as you basically just pull out the data that you put in anyway so you might as well just deal with the numbers directly like this: function dateFormatter(yyyymmdd) { const nameOfMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const year = parseInt(yyyymmdd.substring(0, 4)); const month = parseInt(yyyymmdd.substring(4, 6)); const day = parseInt(yyyymmdd.substring(6, 8)); return `${nameOfMonths[month - 1]} ${day}, ${year}`; } dateFormatter("20240102"); // -> 'Jan 2, 2024' Brian Miller 1 Share Link to comment Share on other sites More sharing options...
0 Brian Miller Posted October 28, 2023 Author Share Posted October 28, 2023 Thanks Don Link to comment Share on other sites More sharing options...
Question
Brian Miller
I've been trying to figure this out but I just can't seem to do it. I'm wondering if someone could help...
I've got a variable with a date that looks like this "20240102" (YYYYMMDD) and I'd like a function that would convert this date into "Jan 2, 2024".
Can someone help me?
Link to comment
Share on other sites
3 answers to this question
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now