moment.js incorrectly interprets the month as the day instead of the actual day

I am currently using moment.js (moment-with-locales.js - v.2.14.1) in my project. My goal is to extract only the date from a datetime string and remove the time. However, when I use the .format() method of moment.js, I receive an incorrect date.

The datetime string that I want to format is:

from ' 08.10.2016 11:00 ' to ' 08.10.2016 '

Here is the code snippet I used in my Angular project:

var date = moment('08.10.2016 11:00').format('DD.MM.YYYY')
console.log(date)

When I run this code, the output I get is:

10.08.2016

instead of 08.10.2016

Interestingly, if I try to retrieve the timestamp (in milliseconds) of my datetime string, it works perfectly fine. For example:

  var dateStart = moment('08.10.2016 19:00', 'DD.MM.YYYY HH:mm').valueOf()
  console.log(dateStart)

This will return:

1475946000000 -> Sat Oct 08 2016 19:00:00 GMT+0200

How can I ensure that I get the correct Date?

Answer №1

The way dates are formatted can vary depending on your region. For example, in the en-US locale, dates are often parsed as "month day year". Therefore, when parsing a date, you need to specify the pattern as well:

var myDate = moment('08.10.2019 11:00','MM.DD.YYYY HH:mm').format('MM/DD/YYYY')

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

Struggling to make CORS function properly on Firefox

Struggling to make a basic example work with the MEAN stack, I've noticed that my DELETE request isn't functioning in Firefox. It seems to be related to CORS. Upon clicking a link to send a DELETE request using angularJS to my ExpressJS backend, ...

What is the threading model utilized by node.js?

Upon establishing a connection with a server operating on node.js, how is the connection handled? Is it one connection per process? Does it follow a connection per thread model? Or does it operate based on request per thread? Alternatively, does it use ...

Utilizing HTML documents instead of images in Owl Carousel 2

I am currently utilizing owl carousel 2 to construct a basic sliding carousel. However, I am only using images at the moment and would like to incorporate HTML files instead. These HTML files contain multiple divs where images can be inserted, and instead ...

What is the best way to find the index of the smallest value in an array using JavaScript?

I recently created this function that currently outputs -1. function sayHello() { let buildingLevelsArray = [11,10,10]; var smallestIndex = buildingLevelsArray.indexOf(Math.max(buildingLevelsArray)); console.log(smallestIndex); } sayHello() ...

The method provided by the FullScreen API is not effective in cancelling the fullscreen mode

After testing my code in Google Chrome, I encountered the following error message: Uncaught TypeError: Object #<HTMLDivElement> has no method 'webkitCancelFullScreen' Interestingly, I also received a similar error while running the code i ...

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...

Navigating through root and sub applications within AngularJS can be managed effectively when housed in sub directories

I currently have two AngularJS applications in place: The first application serves as the base and operates at the root / The second application is a sub-application that needs to be isolated for design purposes, running within a subfolder such as /foo/ ...

Trouble with AJAX Post Request: Missing JSON Response

Below is the AJAX request I have created: var data = modalDom.find("form").serializeObject(); data["returnJson"] = true; $.ajax({ type: "POST", url: "/companies/edit/", data: data, dataType: "JSON", success: function (result) { ...

After performing a Vuex action on one Vue.js component, the update is not reflected on another Vue

I am facing an issue with a component that renders a booking table. When I update my store in another component, the table does not get updated even though the store and computed properties are updated. I suspect that the problem lies with the filter not b ...

Conceal the parent element if there are no elements present within the child element

Look at the markup provided: <div class="careersIntegration__listing" id="careers-listing"> <div class="careersIntegration__accordion"> <div class="careersIntegration__accordion-header"> <span class="careersIntegrat ...

Exploring Vue and Webpack: Optimizing global variables for development and production environments

I have been using vue-cli to create my web application. Throughout the app, I am making use of an API by including it in various places like this: axios.post(API + '/sign-up', data).then(res => { // do something }); The API variable is a c ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Issue with Dropzone not functioning correctly within Vue transition modal

I've implemented a dropzone function in the mounted function, which works perfectly when the dropzone is outside of a modal in the view. However, when I try to use it within a modal with a transition effect, it doesn't work. Any suggestions on ho ...

Issue with the page base and Jquery Ui tabs URL

Having an issue with jqueryui tabs. Here's the code I'm using: // jQuery Tabs $( "#tabs" ).tabs(); // Open correct tab based on URL hash var hash = window.location.hash; var index = $("#tabs a").index($('#link-'+hash.replace('#& ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

Error: The node is unable to parse JSON data through the API

After loading a JSON file as a string, attempting to parse it back to JSON and send it as a response: router.get('/todos', (req,res) =>{ let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{ if (err) ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

What is the best locator to use for this specific input field in the code?

Can someone help me figure out how to locate and fill in another input field in the code snippet below? '<input _ngcontent-tvt-19="" class="form-control ng-pristine ng-valid ng-touched" placeholder="You can search keywords" type="text"> I&apos ...

Show AngularJS ListTreeView condensed

I am currently incorporating an angular tree-view feature into my project. You can find the documentation at the following URL: By default, the nodes are displayed in expanded form. However, I would like them to appear collapsed initially and only expand ...