Converting date string to a new format is not supported by moment js

Having some trouble with formatting dates for MySQL insertion. Here is the current HTML structure:

<strong id="ut-open-date">27/06/2014</strong>

I need to convert the date format to "YYYY-MM-DD" using moment.js library. My code snippet is as follows:

var CreateDate = moment(jQuery('#ut-open-date').html()).format("DD/MM/YYYY");
CreateDate = moment(CreateDate).format("YYYY-MM-DD");

The issue I am facing is that the output changes from 27/06/2014 to 2016-06-03, and I'm not sure why.

I have also tried the following code with the same incorrect result:

var CreateDate = moment(jQuery('#ut-open-date').html()).format("YYYY-MM-DD");

If anyone could provide assistance, it would be greatly appreciated.

Answer №1

By dissecting your code step by step, we can identify where the issue lies:

var CreateDate = moment(jQuery('#ut-open-date').html())

This portion utilizes the default constructor to interpret the date, which is not very reliable and has actually been deprecated. Therefore, moment is attempting to determine the date format.

.format("DD/MM/YYYY");

Here, the data obtained in the previous step is converted into a string with the specific format of DD/MM/YYYY.

CreateDate = moment(CreateDate)

Now you are parsing again without specifying the format, so moment is making an educated guess.

.format("YYYY-MM-DD");

You then instruct it to convert the guessed date into a string formatted as YYYY-MM-DD.

Instead, try this approach:

var CreateDate = moment(jQuery('#ut-open-date').html(), 'DD/MM/YYYY').format('YYYY-MM-DD');

The moment(dateString) method is deprecated; it is recommended to use

moment(dateString, expectedFormat)
instead.

Please refer to the moment documentation here: http://momentjs.com/docs/#/parsing/string-format/

Credit goes to athms for providing the link.

Answer №2

When using moment.js, it is important to specify the format of the date string you want to parse. You can do this by providing a second parameter. Refer to the list of all supported formats. If your desired format is not included in the list, you will need to specify the date format parameter.

moment( jQuery('#ut-open-date').html(), "DD/MM/YYYY" )

Check out the DEMO here

Answer №3

My approach to solve the problem involved utilizing the split function in the following manner:

var RetrieveDate = jQuery('#ut-open-date').text();
var DateList = RetrieveDate.split('/');
RetrieveDate = DateList[2] + '-' + DateList[1] + '-' + DateList[0];

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

A single feature designed to handle various elements

I currently have this HTML code repeated multiple times on my webpage: <form class="new_comment"> <input accept="image/png,image/gif,image/jpeg" id="file" class="file_comment" key=comment_id type="file" name="comment[media]"> <spa ...

Custom sparkline array

In working on my sparkline chart, I have the following code snippet: <div sparkline="" values="4,4,7,5,9,6,4" data-type="line" data-height="80" data-width="100%" data-line-width="2" data-line-color="#dddddd" data-spot-color="#bbbbbb" data-fill-c ...

Convert the easeInExpo function from jQuery easing to vanilla JavaScript and CSS

Currently, I am in the process of converting a piece of code from jQuery to plain JavaScript and CSS. The specific code snippet I am focusing on involves creating easing functions without relying on jQuery. const customEasing = { easeInExpo: function ( ...

Caching HTML5 videos in Google Chrome

I am currently in the process of building a website and have successfully added an HTML5 video. However, I encountered an issue when attempting to change the video file in the background for users to upload a new one. Despite updating the video URL, Chro ...

What is the best way to deactivate an <a> tag in React after it has been clicked?

Is there a way to deactivate the anchor tag below in React once it has been clicked? The onClick function is not functioning on the anchor tag. <td align="left"> <input type="file" accept=".csv,.xlsx,.xls" ...

Discover the magic of parsing JSON child nodes using d3!

Having trouble parsing json data with d3. Below is the json structure: { "name": "Main Course", ... }//json data continues I would like to generate a list based on this data, structured as follows: <ul> <li>Main Course</li> <u ...

Using Bootstrap 5 to display a modal using JavaScript

Creating a sleek gallery using bootstrap 5, and curious about how to activate a bootstrap modal without including "data-bs-..." in the HTML (to prevent repeating those data- attributes multiple times). I have successfully written a functioning JavaScript ...

Include a nested array of objects in the path

I'm looking to enhance the data visualization process by adding a path to the data before plotting the chart. Is there a way to retrieve a specific object by key, even if it's deeply nested, using recursion? I've attempted to do so, but my c ...

The issue I'm facing with ng-show is causing disruptions throughout my

I keep encountering a strange issue where my app freezes whenever I include ng-show in my popover.html. However, when I comment it out, the app functions properly. I'm really struggling to understand what's causing this problem in my code. Below ...

What causes Vue to only update once when there are two closely timed mutations to reactive data?

Can you take a look at this simple example? export default { data() { return { name: "Amy", age: 18, }; }, computed: { combinedDataForWatching() { return { name: this.name, age: this.age, ...

What measures can be taken to keep the rightmost element from moving when hovered over?

While I am generally happy with the layout, there seems to be a slight jump to the left when hovering over the right-most image (you need to click "show images" to view them). Strangely, this issue does not occur with the last row of images. Any suggestion ...

Is there a method to prompt Java to execute NodeJS functions using DNODE?

Visiting the dnode GitHub page at https://github.com/substack/dnode, you'll come across a section that mentions: dnode in other languages These libraries implement the dnode protocol too so you can make RPC calls between scripts written in different ...

Switch up the color of checkboxes with a dropdown menu option

I have an HTML dropdown code and I am trying to trigger a click event when a specific value is selected. Once this value is clicked, I want some checkboxes to change color. <select> <option value="calculate">calculate</option> ...

Encountering a problem with importing a component containing a local image from another package in Next

I am facing an issue with my monorepo which includes a NextJS project and a React library. My goal is to import components from the React project into the NextJS project. Everything seems to be working fine until I try to import a component that contains a ...

Is there a way to configure eslint to recognize and allow the nullish-coalescing assignment syntax?

The "nullish-coalescing assignment" operator, ??=, has been around for some time now in JavaScript. However, it appears that even newer versions of eslint, like 8.38.0, do not seem to recognize it and throw a syntax error regarding the assignment ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

The information submitted through the form is not displaying on the console after being gathered using the post method in Express

When attempting to add products using a form on the admin page, the data (including an image file) is not being displayed in the console as expected. Instead, the following message appears: "{} POST /admin/add-product - - ms - -" Below is th ...

Angular table elements can trigger a click event that redirects to a unique URL generated from the ID of the selected element

In the angular table, every element should be clickable. When any element in the table is clicked, it should use its ID to perform a new search and redirect to the URL based on that ID of the clicked element. Below is the JSON data from the initial URL. It ...

Using JavaScript canvas to zoom and pan with a substantial amount of data (100k-1M objects)

Looking to enhance the zoom and pan capabilities on my Canvas for fast and high-resolution results. Dealing with a large quantity of data makes using CanvasRenderingContext2D.scale() and CanvasRenderingContext2D.translate() along with redrawing too slugg ...

Meld together three columns containing dates, times, and timezones stored as VARCHAR, and convert the values to Coordinated

For specific reasons, we have decided to store certain events' dates in 3 separate columns rather than a single DATETIME column: day_begin (column type: date) hour_begin (column type: time) timezone (column type: varchar) Here is an example row of d ...