• 0

JS Date Conversion


Question

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

  • 0

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

  • 0

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'


 

  • Like 1
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.