What is the process for extracting dates in JavaScript?

I need help extracting the proper date value from a long date string.

Here is the initial date:

Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)

How can I parse this date to: 2020-08-30?

Additionally, I have another scenario:

Tue Aug 25 2020 11:58:04 GMT+0200 (Central European Summer Time)

Is there a way to parse this date to: 11:58?

Thank you for any assistance :) //////////////////////////////////////////////////////////////

Answer №1

If you are confident that your strings will always follow this specific format, a simple solution would be to split them based on spaces:

date = "Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)";
[day_of_week, month, day, year, time, ...tz] = date.split(" ");
tz = tz.join(" "); // recombine the timezone back into one string

You can continue processing it further as needed, but for more in-depth knowledge, consider exploring the Date object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Answer №2

Here is a solution that will get the job done:

function transformDate(dateString) {
  const date = new Date(dateString);
  let month = '' + (date.getMonth() + 1);
  let day = '' + date.getDate();
  const year = date.getFullYear();

  if (month.length < 2) {
    month = '0' + month;
  }

  if (day.length < 2) {
    day = '0' + day;
  }

  return [year, month, day].join('-');
}

// Output will be 2020-08-30
console.log(transformDate('Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)'))

Answer №3

If you find yourself needing to manipulate dates frequently, consider utilizing the Date node library or moment npm package for more functionality.

To obtain the date version:

   moment(your string).format(“YYYY-MM-DD”)

And for retrieving the time:

   moment(your string).format(“HH:mm”)

Answer №4

When it comes to formatting dates in JavaScript, there are a few options available. One common method is to use the following function:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

Alternatively, you can also consider using a third-party library like moment.js (https://momentjs.com/), which is highly recommended for its ease of implementation and extensive features.

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

Using Typescript and React to retrieve the type of a variable based on its defined type

Just getting started with Typescript and could use some guidance. Currently, I'm using React to develop a table component with the help of this library: Let's say there's a service that retrieves data: const { data, error, loading, refetc ...

Add several converted links as variables in each section

The title may not be the clearest, but I am facing a challenge with an ecommerce site that has unmodifiable HTML. My goal is to include additional links for each product displayed on a page showcasing multiple products. Each link should be unique to its re ...

I am currently dedicated to enhancing my background transitions and experimenting with creating smooth fade-ins

I'm almost done with my Weather Forecast page for the FCC challenge. However, I'm not satisfied with how the code for swapping the background works. It just doesn't feel right to me. Unfortunately, I can't figure out how to fix it. Addi ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

Is there a way to create a pixelated render target using THREE JS?

Attempting to set up a basic render target where I render one scene and then use it as a texture over a quad. The demo seems to be pixelated when running, almost like it's rendered on a small screen and stretched across the quad. Below is the code sn ...

Transferring information from an online platform onto pre-arranged sheets for hard copy

Has anyone had success printing from a website? I have some papers that are already printed with checkboxes. These checkboxes need to be filled in based on information entered through a web form or retrieved from a MySQL database. All of this information ...

Removing the JavaScript unicode character 8206 from a text string

I recently transitioned from VB.NET to JavaScript, and I am still getting familiar with the language. I have encountered an issue where a string I'm working with in JavaScript contains Unicode escape characters (0x5206, left-to-right mark) that I need ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Converting an unbroken series of string values into organized key-value pairs for easy reference

I assure you this is not a duplicated question. Despite my attempts with JSON.parse(), it seems to be ineffective. Here's the issue at hand: I recently received assistance from an answer that was both crucial and enlightening. However, the code prov ...

Refrain from revealing AngularJS code before activating it

My AngularJS code displays every time I reload the page https://i.sstatic.net/bzYrr.png Issue: The code appears even when my internet connection is slow or the page does not fully reload. I only want it to display the result. I would appreciate any sugg ...

Error caused by MongoClient TypeError

As a newcomer to NodeJS and someone exploring Dependency Injection for the first time, I encountered an error that led me to seek help. Before asking my question, I reviewed some similar threads on Stack Overflow: [1][2] Upon running my main code, I recei ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Modify the button input value within a PHP script

I am currently working on a piece of code that involves following different users and inserting values from a MySQL table. <td align="center"> <input type="button" name="<?php echo $id; ?>" id="<?php ech ...

recognizing individuals when a particular action is taken or when there is a disruption

Just starting to explore node.js I currently have a PHP/Laravel cms alongside a basic Nodejs game server that generates numbers in a loop To connect my PHP backend with Nodejs, I utilize Socketio and employ Socketio-JWT for user identification On the cl ...

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...