简体   繁体   中英

Node.js converting date string to unix timestamp

I'm attempting to convert a Date String to a unix timestamp in Node.js.

My code below works perfectly on my client but when I run it on my server I get an error:

(node:19260) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: input.substring is not a function

My code:

function dateParser(input) {
    // function is passed a date and parses it to create a unix timestamp

    // removing the '.000' from input
    let finalDate = input.substring(0, input.length - 4);
    return new Date(finalDate.split(' ').join('T')).getTime();
}

Example of my input would be 2017-09-15 00:00:00.000

So why does the above work on my client but not in Node, and how would I duplicate the functionality in node?

Create a date object from your input DateTime string and then use getTime() and divide the result with 1000 to get the UNIX timestamp.

 var unixTimestamp = Math.floor(new Date("2017-09-15 00:00:00.000").getTime()/1000); console.log(unixTimestamp);

I will recommend using momentjs to handle the dates. Using momentjs you could do:

moment().unix(); // Gives UNIX timestamp

If you already have a date and want to get the UNIX timestamp relative to that date, you could do:

moment("2017-09-15 00:00:00.000").unix(); // I have passed the date that will be your input 
// Gives out 1505413800

It gets very productive when handling date/time using momentjs.

A Unix timestamp is the number of seconds from a specific date. The Javascript function getTime() returns the number of milliseconds from the same specific date til the date you specified.

So, if you divide the result of your function by number 1000 you will get the Unix timestamp and convert from milliseconds to seconds. Don't forget to ignore decimal places.

The error message you are receiving is because the value of input is not a string.

2 options with slightly different results if system timezone is not set to UTC

Option 1 - Ignores system timezone

console.log(Math.floor(new Date("2020-01-01").getTime()/1000));

> 1577836800

Option 2 ("moment.js") - Timestamp will differ with system timezone

console.log(moment('2020-01-01').unix());

> 1577854800

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