TKoL
TKoL

Reputation: 13892

using moment.js to set Date and Time from two variables

I have an object, transaction, which has 2 DateTime properties -- one holds the Date, and one holds the Time.

In other words, the Date might be Dec 23, 2019 at 00:00:00, and the time might be something like Jan 1 1970 at 07:36

I'm looking for the best way to combine the date of the first with the time of the second. I have this way, but I don't quite like it:

var transaction = {
    Date: new Date('2019-12-24T00:00:00.000Z'),
    Time: new Date('1754-01-01T07:36:17.647Z')
}

const date = new Date(transaction.Date);
date.setHours(transaction.Time.getHours(), transaction.Time.getMinutes(), transaction.Time.getSeconds(), transaction.Time.getMilliseconds());
console.log(date);

I'm just wondering if Moment.JS has any facilities to do this for me more nicely.

Upvotes: 1

Views: 1013

Answers (1)

Źmicier Jaraševič
Źmicier Jaraševič

Reputation: 371

Not sure that there are such possibilities. Can only suggest the following "simplification":

var transaction = {
    Date: new Date('2019-12-24T00:00:00.000Z'),
    Time: new Date('1754-01-01T07:36:17.647Z')
}

const date = moment(transaction.Date).add(moment.duration(moment(transaction.Time).format("hh:mm:ss")));
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 1

Related Questions