Home > Mobile >  Javascript - Setting Custom Time in Unix Timestamp
Javascript - Setting Custom Time in Unix Timestamp

Time:12-06

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.

CodePudding user response:

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());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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.

  • Related