web-dev-qa-db-fra.com

Comment convertir une date dans Epoch en "Y-m-d H: i: s"?

Comment puis-je convertir la date suivante dans Epoch:

1293683278

à la date lisible suivante:

2010-06-23 09:57:58

utiliser Javascript?

Merci!

14
James Cazzetta
var timestamp = 1293683278;
var date = new Date(timestamp*1000);

var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

alert(year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);

Voir js Date docs pour plus de détails

Autrement: 

var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var iso = date.toISOString().match(/(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})/)
alert(iso[1] + ' ' + iso[2]);
24
deadrunk

Vous pouvez utiliser moment.js pour cela.

moment.unix(1293683278).format('YYYY-MM-DD HH:mm:ss');
12
timrwood

/* Get timestamp */
var timestamp = 1293683278;
document.querySelector("#timestamp").innerHTML = "Timestamp: " + timestamp;

/* Get milisecond from timestamp */
var milisecond = 1293683278 * 1000;    
document.querySelector("#milisecond").innerHTML = "Milisecond: " + milisecond;
  
/* Separate milisecond */
var datetime = new Date(milisecond);

var year    = datetime.getFullYear();
var month   = datetime.getMonth() + 1; // (0-11)
var date    = datetime.getDate();
var hour    = datetime.getHours();
var minute  = datetime.getMinutes();
var second  = datetime.getSeconds();

document.querySelector("#datetime").innerHTML = "Datetime: " + 
  year + "-" + addZero(month) + "-" + addZero(date) + " " + 
  addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);      

// Add 0 if argument < 10
function addZero(i) {
  if (i < 10) {
    i = "0" + i
  };  
  return i;
}
<p id="timestamp"><p>
<p id="milisecond"><p>
<p id="datetime"><p>

0
antelove

Code:

var timestamp = 1293683278;
var d = new Date(timestamp*1000);
alert(
    d.getFullYear() + "-" + 
    ("00" + (d.getMonth() + 1)).slice(-2) + "-" + 
    ("00" + d.getDate()).slice(-2) + " " + 
    ("00" + d.getHours()).slice(-2) + ":" + 
    ("00" + d.getMinutes()).slice(-2) + ":" + 
    ("00" + d.getSeconds()).slice(-2)
);

Format: YYYY-MM-DD HH:II:SS

Résultat: 2010-12-30 07:57:58

Démo: https://jsfiddle.net/NabiKAZ/9ycovfxt/

Remarque: Pour l'heure actuelle, utilisez simplement: var d = new Date(); à la place.

0
Nabi K.A.Z.