Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

I have a string in this format:

var dateTime = "06-17-2015 14:24:36"

I am using moment.js and I am trying to convert it into YYYY-MM-DD HH:mm:ss -> 2015-06-17 14:24:36.

I have tried this method

dateTime = moment( dateTime, 'MM-DD-YYYY HH:mm:ss',true).format("YYYY-MM-DD HH:mm:ss");

But getting dateTime as Invalid Date.

like image 303
Nagarjuna Reddy Avatar asked Jun 17 '15 09:06

Nagarjuna Reddy


People also ask

How do I set the date format in moments?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

What is MomentJS default format?

js default date format to dd/mm/yyyy.


2 Answers

const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>
like image 164
Jayram Avatar answered Sep 23 '22 01:09

Jayram


Use different format or pattern to get the information from the date

var myDate = new Date("2015-06-17 14:24:36");
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));
console.log("Year: "+moment(myDate).format("YYYY"));
console.log("Month: "+moment(myDate).format("MM"));
console.log("Month: "+moment(myDate).format("MMMM"));
console.log("Day: "+moment(myDate).format("DD"));
console.log("Day: "+moment(myDate).format("dddd"));
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format
console.log("Time: "+moment(myDate).format("hh:mm A"));
<script src="https://momentjs.com/downloads/moment.js"></script>

For more info: https://momentjs.com/docs/#/parsing/string-format/

like image 23
Deepu Reghunath Avatar answered Sep 23 '22 01:09

Deepu Reghunath