Comment formater une date JavaScript

Mots clés : javascriptdatedate-formattingjavascript

meilleur 5 Réponses Comment formater une date JavaScript

vote vote

92

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };  var today  = new Date();    console.log(today.toLocaleDateString("en-US")); // 9/17/2016  console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016  console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
// Example 9/17/2016, 1:21:34 PM 
vote vote

86

{ // example 1    let f = new Intl.DateTimeFormat('en');    let a = f.formatToParts();    console.log(a); } { // example 2    let f = new Intl.DateTimeFormat('hi');    let a = f.formatToParts();    console.log(a); }
function join(t, a, s) {    function format(m) {       let f = new Intl.DateTimeFormat('en', m);       return f.format(t);    }    return a.map(format).join(s); }  let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}]; let s = join(new Date, a, '-'); console.log(s);
let d = new Date(2010, 7, 5); let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d); let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d); let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d); console.log(`${da}-${mo}-${ye}`);
vote vote

78

var dateFormat = require('dateformat'); var now = new Date(); dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"); 
Saturday, June 9th, 2007, 5:46:21 PM  
vote vote

70

var d = new Date();  var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes();  // 16-5-2015 9:50 
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +     d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);  // 16-05-2015 09:50 
vote vote

60

var today = new Date().toISOString().slice(0, 10); 
function toJSONLocal (date) {     var local = new Date(date);     local.setMinutes(date.getMinutes() - date.getTimezoneOffset());     return local.toJSON().slice(0, 10); } 
var date = new Date();  function toLocal(date) {   var local = new Date(date);   local.setMinutes(date.getMinutes() - date.getTimezoneOffset());   return local.toJSON(); }  function toJSONLocal(date) {   var local = new Date(date);   local.setMinutes(date.getMinutes() - date.getTimezoneOffset());   return local.toJSON().slice(0, 10); }  // check out your devtools console console.log(date.toJSON()); console.log(date.toISOString()); console.log(toLocal(date));  console.log(toJSONLocal(date));

Questions similaires