What is the best way to change this date format into a JavaScript Date object?

Dealing with a service that gives me a strange date format, and I'm struggling to find a simple way to convert it into a JS Date Object. I have some important logic to implement with these dates, so converting them is crucial.

The date format provided by the service looks like this: 02/Dec/2020:23:58:15 +0000.

I would greatly appreciate any assistance. Thank you in advance!

Answer №1

To properly parse the date, replace the first instance of : with a space

const str = "02/Dec/2020:23:58:15 +0000"

console.log(new Date(str.replace(/:/," "))); // modify only the first colon

A more stable version requires additional steps - tested on Safari, Chrome, and Firefox

const monthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
const re = /(\d{2})\/(\w{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) (.*)/;

const makeDate = str => {
  const [_, dd, mmm, yyyy, hh, min, ss, tz] = str.match(re)
  const tzStr = [tz.slice(0, 3), ':', tz.slice(3)].join(''); // create ±hh:mm
  const mm = monthNames.indexOf(mmm.toLowerCase()); // English language only
  const isoString = `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}${tzStr}`
  console.log(isoString)
  return new Date(isoString)
};

const str = "02/Dec/2020:23:58:15 +0000"
const d = makeDate(str);
console.log(d)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reorganizing form input array following the dynamic addition and deletion of fields

Currently, I am in the process of developing a custom WordPress widget that allows users to add and remove blocks of input fields in the widget back-end. While I have managed to make the add and remove functionality work smoothly, I am facing an issue when ...

Preserving the active tab in JQuery while dynamically regenerating tabs due to database updates

I have one default static tab and two dynamic tabs that are generated based on database records. Whenever there is a change in the database, I use the $('.dynamic').remove(); JQuery remove method to refresh the elements dynamically. The dynamic ...

The execution of the Mocha test script is hindered by a socket.io issue causing it to

Running my tests (mocha) by typing npm run test in the console was working fine until I pulled down some code from my team. There seems to be an issue now. We are building an app that utilizes Socket.io, and for some reason, it appears in the command promp ...

I am encountering issues with my PostCSS plugin not functioning properly within a Vue-cli 3 project

I developed a custom postcss plugin that was working perfectly according to the postcss guidelines until I tried to implement it in a real project. For reference, here's the plugin on GitHub My goal is to integrate it into a Vue-cli app using Webpac ...

What is the best way to integrate a PHP page with its own CSS and JavaScript into a Wordpress page?

I'm facing a challenge with integrating a dynamic PHP table into my WordPress page. Despite working perfectly when opened locally, the CSS and JavaScript used to create the table are not functioning properly when included in a WordPress page via short ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

Serving Files in Express JS: the benefits of serving files directly from memory compared to serving static

Should I keep images and other assets in memory or serve them from static assets? Will often-requested static assets be stored in memory? Does anyone have insight into the performance implications of this decision? ...

ajax - Text not appearing in Google's cached version

My website retrieves content using MS AJAX from an ASP.NET webservice. However, when I check the cached version on Google, I notice that the initial text is not displayed. I am wondering what would be the most effective method to ensure the website's ...

Transmit a file using multipart with XMLHttpRequest

Is it possible to use XMLHttpRequest to send a multipart file to a servlet? I am currently working on a form that needs to be submitted as multipart, but I am not receiving a response after successfully uploading it. It is important that the process happe ...

ASP.NET CodeBehind Fails to Recognize Changes in TinyMCE Textarea

I have multiple <asp:TextBox TextMode="MultiLine"> elements on a webpage. Initially, I populate them using VB code behind and then convert them into TinyMCE editors with the help of the jQuery TinyMCE plugin. Each text box has an associated button fo ...

Is it possible to resolve the error message "Uncaught TypeError: Cannot read property 'node' of undefined" when utilizing d3-tip with npm?

After installing d3": "^3.5.17" and "d3-tip": "^0.7.1" via npm (d3-tip documentation), the following code was added to my index.js file: var d3 = require('d3'); var d3tip = require('d3-tip')(d3); console.log('d3 version', d3. ...

Increment or decrement a number using setTimeout in JavaScript

Having trouble with incrementing and decrementing a number using a timer in my code. It seems to not be working properly... let num = 0, maxNum = 5, timerFunc = function() { if (num < maxNum) { num++; console.log(num); //working f ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

Display the current username using Angular authenticationorDemonstrate how

I've been modifying a login script created by someone else. My objective was to incorporate the use of ng-option instead of input. I successfully implemented this, as shown in the example. However, after logging in, I'm unable to view the user&ap ...

What is the method for including preset text within a search bar?

My current issue is as follows: When the searchbox is focused, it appears like this: -------------------- -------------------- Upon exiting the searchbox, a string will automatically be added to it: -------------------- Search -------------------- I a ...

Is it possible for a function parameter to utilize an array method?

Just starting to grasp ES6 and diving into my inaugural React App via an online course. Wanted to share a snag I hit along the way, along with a link to my git repository for any kind souls willing to lend a hand. This app is designed for book organization ...

MUI's lazy loading feature can interfere with the functionality of useEffect

I have integrated a tabs interface using React's MUI library (https://mui.com/material-ui/react-tabs/#fixed-tabs) Here is the code I am using: import * as React from 'react'; import PropTypes from 'prop-types'; import SwipeableVie ...

Automated service worker upgrade procedure

Currently, I have some concerns regarding the update process of the service worker used in my project. Within this project, there are two key files associated with the service worker: The first file, "sw.js", is located in the root of the website and is i ...

Adjust the translateX value and element size based on either the parent element's size or the window's dimensions

Is this question specific enough to relate to others' problems? My issue involves two elements, a child and a parent, with the child element rotating around the parent using CSS animations. <div class="planet"> <div class="moon"></di ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...