Transform the date from toLocaleString to a different Date format

I am currently dealing with a situation where I need to convert a date format using the toLocaleString method.

const localDate = proDate.toLocaleString("en-GB").replace(/,/g, "");

In this case, proDate refers to a new Date(someDate) object.

Later in my code, I face the challenge of converting localDate back to the new Date() format.

Although I attempted to use new Date(localDate), it resulted in an invalid date error.

The current format of localDate is 18/03/2023 08:45:47.

In my code, I do not have direct access to proDate when trying to perform the conversion on localDate.

Is there any alternate solution or workaround for this issue?

Answer №1

If you're familiar with the format, using a regular expression to parse it is a viable option.

const localDate = new Date().toLocaleString("en-GB").replace(/,/g, "");
console.log(localDate);
const [, day, month, year, hours, minutes, seconds] = localDate.match(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})/);
const date = new Date(year, month - 1, day, hours, minutes, seconds)
console.log(date);

Another approach, as recommended by RobG, is to simply match consecutive digits:

const localDate = new Date().toLocaleString("en-GB").replace(/,/g, "");
const [day, month, year, hours, minutes, seconds] = localDate.match(/\d+/g);
const date = new Date(year, month - 1, day, hours, minutes, seconds)
console.log(date);

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

Having trouble with jQuery scrollTop not working after loading content with ajax?

When the html content is loaded via ajax, I need to scroll to a specific element. This element has the attribute data-event-id="". However, there are instances when the variable $('.timelineToolPanel[data-event-id="'+id+'"]').offset().t ...

Having trouble retrieving the pathname of a nested route within middleware.js in next js version 14

I am currently referring to the official App Router documentation for Authentication on this page My goal is to extract the pathname from the next URL export function middleware(request) { console.log('now we are in middleware'); const { ...

Tips for utilizing the "g" element in SVG within CoffeeScript to rotate an object in D3

I'm experimenting with creating a design similar to the following SVG code snippet: <svg width="12cm" height="4cm" viewBox="0 0 1200 400" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Example rect02 - rounded rectangles&l ...

Undefined scope

angular.module('CrudApp', []). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/', { templateUrl: 'assets/tpl/lists.html', controller: ListCtrl }). when('/add-user&apos ...

Is it possible to use $.post and $.get to update the title without changing the logging functionality?

Here is a portion of my code where I am posting to a link. The issue I am facing is that it allows me to change the title, but for some reason, it does not call the function info() with the argument provided. Additionally, it does not log anything in the c ...

When you log a JavaScript array after making a call using $.ajax, it may return an index

I am experiencing an issue with my array of 10 elements. When I log their key, value pairs in a loop, they are correctly ordered. $.each( sArray, function(i, k) { log(i, k); // log(i, k) returns correctly // [0] ELEMENT ONE // [1] ELEMENT TW ...

Dynamic background color changes with each click or scroll

I have successfully created a function to Generate Background Colors, but the problem arises when I interact with the page by clicking or scrolling, causing the background colors to change repeatedly. HTML: <ion-button shape="round" color="clear" [ngS ...

Creating an Engaging Discord Bot: A Step-by-Step Guide

I'm in the process of developing a Discord bot and I'm interested in adding a unique feature to it. I want to create an interactive system where users can request help through DM with the bot, and the support team can respond through the bot as w ...

Issue with karma-ng-html2js-preprocessor failing to generate modules

Struggling to configure the karma-ng-html2js-preprocessor. While Karma has been successfully detecting all my JavaScript files, it's having trouble generating a module from the HTML preprocessor. Take a look at my options object below. I've spec ...

Adjusting the shadow on the inserted image

Currently, I am using fabric.js to manipulate images that are added to my canvas. The issue I am facing is with the shadow around the image not being even. The code I have tried so far is displayed below, but you can view what I am aiming for by clicking h ...

When the Promise object is assigned to the img [src], the image may occasionally be set to null

I incorporate Angular into my Electron application. One of the components in my app contains an array called files, where each element is an object with a member named preview. This preview member is a Promise object that returns a file:// object. <mat- ...

Unable to Pause Video with Javascript

I have a project with a video that plays in a continuous loop. Below is the HTML code for the video tag: <video playsinline autoplay muted loop id="myVid"> <source src="River.mp4" type="video/mp4"> </video> My goal is to make the vi ...

Merging an AppBar and Drawer in Material UI for a seamless user interface design

I am working on integrating an AppBar component with a drawer feature. Here is the code for the AppBar: import React from "react"; import PropTypes from "prop-types"; import { withStyles } from "material-ui/styles"; import AppBar from "material-ui/AppBar" ...

Tips for effectively linking a ReactJS component to Redux with the help of react-redux

Currently, I am in the process of establishing my initial connection between a React component and Redux in order to fetch data from my node API. Although this component is currently simple, it has potential for expansion to include subcomponents that wil ...

Retrieve the content following a successful loading of the remote URL

I have been utilizing this function to retrieve content from a Remote URL function fetchContent($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $scrapedPage = curl_exec($ch); curl_close($ch); $content = $scrapedPage; return ...

Node-fetch enables dynamic requests

Seeking to retrieve real-time data from a fast-updating API has posed a challenge for me. The issue lies in my code constantly returning the same value. I've experimented with two approaches: var fetch = require("node-fetch"); for(let i=0; i<5; i+ ...

Newbie Inquiry Renewed: What is the best way to convert this into a functional hyperlink that maintains the data received from the ID tag?

I have no prior training etc. If you are not willing to help, please refrain from responding as I am simply trying to learn here. <a id="player-web-Link">View in Depth Stats</a> This code snippet loads the following image: https://i.stack.i ...

I am looking to superimpose one rectangle over another rectangle

I am looking to create something similar using CSS and TypeScript/JavaScript: Could someone please guide me on how to achieve this? My attempt with a flex container looks like this: I am new to front-end development. Can anyone point out what I might be ...

Is it possible to send a ternary expression inside a component as a prop based on whether the condition is true or false?

Is it possible to include a ternary expression inside a component and pass it as a prop depending on whether the condition is true or false? <ExperienceList onUserToggle={this.onUserToggle} jobs={this.state.jobs[this.state.value]} { th ...

What is the proper way to execute a script and transmit arguments when the client is connected via a socket?

Is it possible to execute a script that passes arguments to a connected client using Socket.IO? Here's an example scenario: var io = require('socket.io').listen(http); io.sockets.on('connection', function (client) { console ...