Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js concatenate date and time

I have four fields in a form, some containing an initial date and the end date (dd / mm / yyyy) and the others contain the start time and the end time (hh: ss).

The value of these fields I use to get the date and time with moment.js such as this:

initialdate = moment( $('input#start_date').val(), 'DD/MM/YYYY' ); start_time = moment( $('input#start_time').val(), 'HH:mm'); enddate = moment( $('input#enddate').val(), 'DD/MM/YYYY' ); end_time = moment( $('input#end_time').val(), 'HH:mm'); 

What I intend is to then get the difference in seconds between the two dates, concatenating the starting date and time and the ending date and time. I have tried to do this, but to no avail:

start = initialdate + start_time; end = enddate + end_time; tracker = moment.duration( end.diff(start) ).asSeconds(); 
like image 878
grankan Avatar asked Feb 22 '17 23:02

grankan


People also ask

How do you pass the moment to the date?

js parsing date and time. We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.

How do you find Moment with current time?

To get the current date and time, just call javascript moment() with no parameters like so: var now = moment();


1 Answers

Concatenate the date and time strings and parse them as one, e.g.

var date = '23/02/2017';  var time = '15:42';    var dateTime = moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');    console.log(dateTime.format('YYYY-MM-DD HH:mm'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
like image 76
RobG Avatar answered Sep 24 '22 10:09

RobG