Javascript Formattazione Date

Molto spesso mi capita di formattare le date in Javascript e quindi ho deciso di tenerne traccia con questo articolo.

Data corrente (get date)

new Date()

//Risultato
"Tue Jul 23 2019 19:37:00 GMT+0200 (Central European Summer Time)"

Stampare la data e ora corrente

let current_datetime = new Date()
console.log(current_datetime.toString())

 // Risultato
"Tue Jul 23 2019 19:22:10 GMT+0200 (Central European Summer Time)"

Formattazione Data e Ora

Formato dd-mmm-yyyy

let current_datetime = new Date()
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getFullYear()
console.log(formatted_date)

// Risultato
23-7-2019

Convertire il numero di mesi con i nomi

const months = ["Gennaio", "Febbraio", "Marzo","Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
let current_datetime = new Date()
let formatted_date = current_datetime.getDate() + "-" + months[current_datetime.getMonth()] + "-" + current_datetime.getFullYear()
console.log(formatted_date)

//Risultato
23-Luglio-2019

Formato yyyy-mm-dd

let current_datetime = new Date()
let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate()
console.log(formatted_date)

//Risultato
2019-7-23

Formato yyyy-mm-dd hh:mm:ss

let current_datetime = new Date()
let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds() 
console.log(formatted_date)

//Risultato
2019-7-23 19:30:6

Aggiungere gli zeri a sinistra

function appendLeadingZeroes(n){
  if(n <= 9){
    return "0" + n;
  }
  return n
}

let current_datetime = new Date()
console.log(current_datetime.toString());
let formatted_date = current_datetime.getFullYear() + "-" + appendLeadingZeroes(current_datetime.getMonth() + 1) + "-" + appendLeadingZeroes(current_datetime.getDate()) + " " + appendLeadingZeroes(current_datetime.getHours()) + ":" + appendLeadingZeroes(current_datetime.getMinutes()) + ":" + appendLeadingZeroes(current_datetime.getSeconds())

console.log(formatted_date);

//Risultato
2019-07-23 19:30:06

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *