skip to Main Content

Struggling to display a date in javascript that is retrieved from a postgres database and returned via python.

When I simply console.log the variable I get back from my GET request, it is in this format:

Thu, 12 Sep 2024 00:00:00 GMT

I’m simply attempting to display that as:

09/12/24

(I don’t know where the 00:00:00 GMT portion is coming from, but essentially I just want to discard that. It seems to be affecting my conversions for some reason.)

I AM using moment.js, but have not been able to get it to display the correct date. It always displays 1 day prior (9/11/24).

What would be the easiest method to simply display that returned datetime string as "09/12/24" (the time portion will never need to be accounted for)?

2

Answers


  1. Chosen as BEST ANSWER

    I took the recommendation of the collective to remove momentjs as a dependency, and am now using dayjs instead.

    Being almost a direct drop-in replacement, the solution was minimal with dayjs:

    let s = dayjs(req.req_start, 'ddd, DD MMM YYYY HH:mm:ss')
    s = s.format('MM/DD/YY')
    

  2. The issue you’re experiencing is due to timezone conversion. When you parse a date string that includes a timezone (like "Thu, 12 Sep 2024 00:00:00 GMT"), JavaScript and Moment.js convert it to your local timezone by default. If your local timezone is behind GMT (e.g., in the U.S.), this conversion can shift the date back by one day, causing it to display as "09/11/24" instead of "09/12/24".

    To fix this, you can parse and format the date in UTC to prevent any timezone adjustments. Here are a few methods to achieve the desired format:

    // Parse the date string as UTC
    const date = moment.utc('Thu, 12 Sep 2024 00:00:00 GMT');
    
    // Format the date in UTC
    const formattedDate = date.format('MM/DD/YY');
    
    console.log(formattedDate); // Outputs: 09/12/24
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

    Since Moment.js is now in maintenance mode, you might consider using modern libraries like Luxon or Day.js for dates in general. However this can easily achieved without any library:

    const date = new Date('Thu, 12 Sep 2024 00:00:00 GMT');
    const formattedDate = date.toLocaleDateString('en-US');
    
    console.log(formattedDate); // Outputs: 09/12/24
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search