Parse String to Date with Moment.Js

Parse string to date with moment.js

You need to use the .format() function.

MM - Month number

MMM - Month word

var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');

FIDDLE

Converting String to Date using Moment.js returning Invalid Date

Try specifying format inside moment() , the format that you receive so that moment will parse it to a valid date.

let data = "21. 5. 2020";let res = moment(data, "DD. M. YYYY"); // this will be valid moment date nowconsole.log(res.format("DD-MM-YYYY"));
<script src="https://momentjs.com/downloads/moment.js"></script>

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

Convert string to date using moment.js

In your constructor add: this.requestDate = moment(values.requestDate, "MM-DD-YYYY").toDate();

See the documentation:

  • https://momentjs.com/docs/#/parsing/string-format/
  • https://momentjs.com/docs/#/displaying/as-javascript-date/

Moment.js cannot parse string to date

I solved the problem by reading the docs again. The right way is:

moment('14. November 2018', 'DD. MMMM YYYY');

Parse and format custom date string Moment.js

To anyone interested, the solution was making HH:MM:SS lower case and dd uppercase.

Final string and format was var date = moment("Wed Dec 24 00:00:00 -0800 2014","ddd MMM DD hh:mm:ss ZZ YYYY").format('DD');.

moment.js parse date with strict format and locale

The issue is that you are not properly importing the localization, have a look at Loading locales in NodeJS section in the docs.

The linked code works if you put:

import moment from "moment/min/moment-with-locales";

instead of

import moment from "moment";


Related Topics



Leave a reply



Submit