How to set time with date in momentjs

Does momentjs provide any option to set a time with a specific time?

var date = "2017-03-13";
var time = "18:00";

var timeAndDate = moment(date).startOf(time);

console.log(timeAndDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Run codeHide result

enter image description here

+17
source share
1 answer

Moment.js does not provide a way to set the time of an existing moment through a string. Why not just combine the two:

var date = "2017-03-13";
var time = "18:00";

var timeAndDate = moment(date + ' ' + time);

console.log(timeAndDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Run codeHide result

In addition, you can use two Moment objects and use the get and set methods. Although this is a much more verbose option, it can be useful if you cannot use concatenation:

let dateStr = '2017-03-13',
    timeStr = '18:00',
    date    = moment(dateStr),
    time    = moment(timeStr, 'HH:mm');

date.set({
    hour:   time.get('hour'),
    minute: time.get('minute'),
    second: time.get('second')
});

console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Run codeHide result
+39
source

Source: https://habr.com/ru/post/1015348/


All Articles