0

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.

2 Answers2

0

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 (e.g. hours 0-23, minutes 0-59).

RobG
  • 142,382
  • 31
  • 172
  • 209
-1

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.

  • Produces `NaN` in Safari, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Even if parsed correctly, it takes a UTC date, appends a time, parses it as local, then generates a UTC time value so will differ from the local date for the period of the local offset from midnight. – RobG Dec 05 '21 at 20:18