Home > front end >  convert 13 digit time code to date and time stamp using moment js and get the difference between the
convert 13 digit time code to date and time stamp using moment js and get the difference between the

Time:09-17

I have start time and end time as follows

var starttime=1631108701000
var endtime=1631116762000
var sessionstart=moment.unix(startTime);
var sessionend=moment.unix(endTime);
var ms = moment(sessionend,"DD/MM/YYYY HH:mm:ss").diff(moment(sessionstart,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var timeelapsed = Math.floor(d.asHours())   moment.utc(ms).format(":mm:ss");

goal is to display the starttime and endtime with proper date time stamp and disply the difference between then like 2hours16minutes53seconds or 02:16:53.The above code returns faulty data. How do I fix it?

CodePudding user response:

The below code worked for me

var sessionstart= moment.unix(startTime/1000).format("DD/MM/YYYY HH:mm:ss");
var sessionend= moment.unix(endTime/1000).format("DD/MM/YYYY HH:mm:ss");
var ms = moment(sessionend,"DD/MM/YYYY HH:mm:ss").diff(moment(sessionstart,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var timeelapsed = Math.floor(d.asHours())   moment.utc(ms).format(":mm:ss");

By default moment.unix() expects in seconds so we need to divide by 1000 and format as per requirement.

CodePudding user response:

You could also have a look at this approach. First convert unix epoch milliseconds to seconds. Then use moment's diff function to calculate the respective units. Notice that I am adding corresponding units after each diff to get the accurate difference.

const startTime = "1631108701000";
const endTime = "1631116762000";

// Converting epoch milliseconds to seconds
const startUnixTime = moment.unix(startTime / 1000);
const endUnixTime = moment.unix(endTime / 1000);

// hour difference
const hourDiff = endUnixTime.diff(startUnixTime, "hours");
startUnixTime.add(hourDiff, "hours");

// minute difference
const minDiff = endUnixTime.diff(startUnixTime, "minutes");
startUnixTime.add(minDiff, "minutes");

// second difference
const secDiff = endUnixTime.diff(startUnixTime, "seconds");

// Actual Input dates
const startDate = moment(startUnixTime).format("DD-MM-YYYY hh:mm:ss");
const endDate = moment(endUnixTime).format("DD-MM-YYYY hh:mm:ss");
console.log("Input start date", startDate);
console.log("Input end date", endDate);

// Difference in hours, minutes, seconds
console.log(hourDiff, minDiff, secDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

  • Related