Get hour minutes and seconds in javascript

Asked

Viewed 295 times

-1

Would you like to know how I do in Javascript to get the time? A number that represents the current date and time and seconds. I know we got the object for date and time and seconds through:

const data = new Date();

Not I understood this very well.

1 answer

1


In Javascript you can save a date to an object (instance) Date. This instance has methods from which you can extract its components such as date, year, hours, etc...

You can read more about it here at MDN, but to give an example with hours you can extract and create an array that then converts into a string with the two points separating the values:

const data = new Date(); // momento atual 
const horas = data.getHours();
const minutos = data.getMinutes();
const segundos = data.getSeconds();

const hhmmmss = [horas, minutos, segundos].join(':');
console.log(hhmmmss);

However, for this type of representation you can also use the toLocaleTimeString that gives you exactly this formatted for the locale you want:

const data = new Date(); // momento atual 
console.log(data.toLocaleTimeString('pt-BR'));

  • 1

    I get it, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.