it-swarm.com.de

Wie kann ich ein Datum in der Epoche in "Y-m-d H: i: s" in Javascript konvertieren?

Wie kann ich folgendes Datum in Epoche umwandeln:

1293683278

zu folgendem lesbaren Datum:

2010-06-23 09:57:58

mit Javascript?

Vielen Dank!

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);

Weitere Einzelheiten finden Sie in js Date docs

Ein anderer Weg:

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

Sie können dazu moment.js verwenden.

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

Ergebnis: 2010-12-30 07:57:58

Demo: https://jsfiddle.net/NabiKAZ/9ycovfxt/

Hinweis: Verwenden Sie für die aktuelle Uhrzeit einfach: var d = new Date();.

0
Nabi K.A.Z.