简体   繁体   中英

Javascript - Setting Custom Time in Unix Timestamp

I'm working on a program that takes input from a user for a time. The program will take the information and automatically generate a Unix Timestamp using the current date as the date in the timestamp.

For example:

Daniel wants to generate a Unix Timestamp for 8:30 AM on Christmas Day. He runs a command /unix 8:30 , and the console prints out 1640421000 .

What's the best way to achieve this? I understand how to generate a Unix Timestamp, but how do I edit just the time to the user input. Any help would be greatly appreciated.

I just went with the following:

const time = interaction.options.getString('time');
const date = new Date().toISOString().slice(0, 10);

console.log(Math.round(new Date(`${date} ${time}:00`).getTime()/1000));

Seems to work for me.

You can create a Date for the current date, set the time as required, then generate a time value in seconds.

If the user will always enter H:mm and you don't need to validate the input, then the following will do:

 let time = '8:30'; let tv = new Date().setHours(...(time.split(/\D/)), 0) / 1000 | 0; // Check value console.log(new Date(tv * 1000).toString());

However, the input should be validated (eg hours 0-23, minutes 0-59).

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