Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time to DateTime using moment js

I have time in HH:mm format like 13:15. I want to convert it into YYYY-MM-DD HH:mm using moment.js .

I tried the following code.

var t = "13:56"; 
var cdt = moment(t).format('YYYY-MM-DD HH:mm');
alert(cdt);

I wanted output with the current date and given time like 2015-21-05 13:56

like image 637
Arockiaraj Avatar asked May 21 '15 09:05

Arockiaraj


People also ask

How do I get time from moment to datetime?

With the diff function, we can calculate the difference between two datetime objects. const moment = require('moment'); let d1 = moment('2018-06-12'); let d2 = moment('2018-06-28'); let days = d2. diff(d1, 'days'); console. log(`Difference in days: ${days}`); let hours = d2.

How do you use moments to date?

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.

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.

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.


1 Answers

You need to use string-format moment constructor to pass string and format in which input string is.

Use

var t = "13:56"; 
var cdt = moment(t, 'HH:mm');
console.log(cdt.toDate());
console.log(cdt.format('YYYY-MM-DD HH:mm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>
like image 119
Satpal Avatar answered Sep 28 '22 04:09

Satpal