简体   繁体   中英

How to convert the DD-MM-YYYY HH:mm format to epoch time using moment or js?

I have a date time picker and it omits date in format of a DD-MM-YYYY HH:mm a format. I want to convert it into epoch time to store it in the database backend. I have tried using the following methods so far, but all of them return NaN as output:

var loadingPlannedUnTime = this.state.loadingPlannedUnTime;
console.log("normal conversion"+loadingPlannedUnTime);
//returns 9-08-2020 15:08:00

//Moment method
var loadingPlannedUnTime = moment(this.state.loadingPlannedUnTime).unix();
console.log("moemnt"+loadingPlannedUnTime)
//Returns NaN

//JS getTime() method 
var pickupDateTime = new Date(this.state.loadingPickupTime);
var loadingPickupTime = pickupDateTime.getTime();
console.log("new date and gettime"+loadingPickupTime)
//Returns NaN

What is the correct method to convert it to epoch time?

https://momentjs.com/docs/

If you know the format of an input string, you can use that to parse a moment.

moment("12-25-1995", "MM-DD-YYYY");

 const x = moment('24-12-2019 09:15', "DD-MM-YYYY hh:mm"); console.log(x.format())
 <script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>

const matches = loadingPlannedUnTime.match(/(\d{1,2})-(\d{1,2})-(\d{2,4}) (\d{1,2}):(\d{1,2}):(\d{1,2})/);
if (!!matches) {
    // new Date(year, month, day, hours, minutes, seconds, milliseconds)
    const epoch = new Date(matches[3], matches[2] - 1, matches[1], matches[4], matches[5], matches[6]).getTime();
    console.log(epoch);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM