Domanda

Io sono l'archiviazione di tempo in un database MySQL come un timestamp Unix e che viene inviato ad un codice JavaScript. Come faccio a ottenere solo il tempo fuori di esso?

Per esempio, in HH / MM / SS formato.

È stato utile?

Soluzione

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

Per ulteriori informazioni riguardanti l'oggetto Date, si prega di fare riferimento a NDP o il ECMAScript 5 specifica .

Altri suggerimenti

function timeConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp * 1000);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var hour = a.getHours();
  var min = a.getMinutes();
  var sec = a.getSeconds();
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  return time;
}
console.log(timeConverter(0));

funziona

JavaScript in millisecondi, quindi dovrete prima convertire il timestamp UNIX da secondi in millisecondi.

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

Io ho un debole per Date.format() biblioteca di Jacob Wright, che implementa la formattazione data di JavaScript lo stile di date() funzione.

new Date(unix_timestamp * 1000).format('h:i:s')

Ecco la soluzione più breve-liner formato secondi il hh:mm:ss:

/**
 * Convert seconds to time string (hh:mm:ss).
 *
 * @param Number s
 *
 * @return String
 */
function time(s) {
    return new Date(s * 1e3).toISOString().slice(-13, -5);
}

console.log( time(12345) );  // "03:25:45"
  

Date.prototype.toISOString() restituisce in tempo   semplificato esteso ISO 8601 formato, che è sempre lunga 24 o 27 caratteri (es YYYY-MM-DDTHH:mm:ss.sssZ o   ±YYYYYY-MM-DDTHH:mm:ss.sssZ rispettivamente). Il fuso orario è sempre   spostamento origine UTC.

NB .: Questa soluzione non richiede alcuna librerie di terze parti ed è supportato in tutti i browser moderni e motori JavaScript.

Usa:

var s = new Date(1504095567183).toLocaleDateString("en-US")
// expected output "8/30/2017"   

e per il tempo:

var s = new Date(1504095567183).toLocaleTimeString("en-US") 
// expected output "3:19:27 PM"`

Date.prototype.toLocaleDateString ()

Mi piacerebbe pensare di utilizzare una libreria come momentjs.com , che rende questo molto semplice:

In base a un timestamp Unix:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );

In base a una stringa data di MySQL:

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );

UNIX timestamp è il numero di secondi dal 00:00:00 UTC del 1 ° gennaio 1970 (in base al Wikipedia ).

Argomento dell'oggetto Date in JavaScript è il numero di millisecondi dal 00:00:00 UTC del 1 gennaio 1970 (secondo W3Schools JavaScript documentazione ).

Vedere codice qui sotto per esempio:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

dà:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

Moment.js , è possibile ottenere ora e la data in questo modo:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");

E si può ottenere solo il tempo di utilizzare questo:

var timeString = moment(1439198499).format("HH:mm:ss");

Il problema con le soluzioni citate è, che se ora, minuti o secondi, ha una sola cifra (cioè 0-9), il tempo sarebbe sbagliato, ad esempio potrebbe essere 2: 3:. 9, ma dovrebbe piuttosto essere 02:03:09

questa pagina sembra essere una migliore soluzione per utilizzare il metodo "toLocaleTimeString" di Data.

Un altro modo -. Da un ISO 8601 data

var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
alert(iso[1]);

Nel momento in cui si deve usare unix timestamp:

var dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");

minor soluzione one-liner formattare secondi come hh: mm: ss: variante:

console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));
// "2019-02-04 20:34:12"

La soluzione moderna che non ha bisogno di una libreria di 40 KB:

Intl.DateTimeFormat è la non -culturally modo imperialista per formattare una data / ora.

// Setup once
var options = {
    //weekday: 'long',
    //month: 'short',
    //year: 'numeric',
    //day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );

// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );

In base alla risposta di @ shomrat, ecco un frammento che scrive automaticamente datetime come questo (un po 'simile a quella data StackOverflow per le risposte: answered Nov 6 '16 at 11:51):

today, 11:23

o

yersterday, 11:23

o (se l'anno diverso, ma stesso rispetto ad oggi)

6 Nov, 11:23

o (se un altro anno rispetto ad oggi)

6 Nov 2016, 11:23

function timeConverter(t) {     
    var a = new Date(t * 1000);
    var today = new Date();
    var yesterday = new Date(Date.now() - 86400000);
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
        return 'today, ' + hour + ':' + min;
    else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
        return 'yesterday, ' + hour + ':' + min;
    else if (year == today.getFullYear())
        return date + ' ' + month + ', ' + hour + ':' + min;
    else
        return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}
function getTIMESTAMP() {
      var date = new Date();
      var year = date.getFullYear();
      var month = ("0"+(date.getMonth()+1)).substr(-2);
      var day = ("0"+date.getDate()).substr(-2);
      var hour = ("0"+date.getHours()).substr(-2);
      var minutes = ("0"+date.getMinutes()).substr(-2);
      var seconds = ("0"+date.getSeconds()).substr(-2);

      return year+"-"+month+"-"+day+" "+hour+":"+minutes+":"+seconds;
    }
//2016-01-14 02:40:01

Il mio timestamp è essere recuperati da un backend PHP. Ho provato tutti i metodi di cui sopra e non ha funzionato. Ho poi sono imbattuto in un tutorial che ha funzionato:

var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());

le modalità sopra genereranno questo risultato

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM

C'è un sacco di metodi che funzionano perfettamente con timestamp. Cant tutti List

Fare attenzione al problema a zero con alcune delle risposte. Ad esempio, il timestamp 1439329773 sarebbe erroneamente convertito 12/08/2015 0:49.

Vorrei suggerire di utilizzare il seguente per superare questo problema:

var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);

Ora si traduce in:

12/08/2015 00:49
// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());

Vedere Data / Epoch Converter .

È necessario ParseInt, altrimenti non avrebbe funzionato:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;

È possibile utilizzare la seguente funzione per convertire il timestamp a HH:MM:SS formato:

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

Senza passare un separatore, utilizza : come separatore (default):

time = convertTime(1061351153); // --> OUTPUT = 05:45:53

Se si desidera utilizzare / come separatore, basta passarlo come secondo parametro:

time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55

Demo

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

document.body.innerHTML = '<pre>' + JSON.stringify({
    920535115 : convertTime(920535115, '/'),
    1061351153 : convertTime(1061351153, ':'),
    1435651350 : convertTime(1435651350, '-'),
    1487938926 : convertTime(1487938926),
    1555135551 : convertTime(1555135551, '.')
}, null, '\t') +  '</pre>';

Si veda anche questa Fiddle .

function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
     var hour = a.getUTCHours();
     var min = a.getUTCMinutes();
     var sec = a.getUTCSeconds();
     var time = hour+':'+min+':'+sec ;
     return time;
 }

Se si desidera convertire Unix tempo determinato, di vere e proprie ore, minuti e secondi, è possibile utilizzare il seguente codice:

var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;
 function getDateTimeFromTimestamp(unixTimeStamp) {
    var date = new Date(unixTimeStamp);
    return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
  }

var myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00
function getDateTime(unixTimeStamp) {

    var d = new Date(unixTimeStamp);
    var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
    var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
    var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();

    var time = h + '/' + m + '/' + s;

    return time;
}

var myTime = getDateTime(1435986900000);
console.log(myTime); // output 01/15/00

Codice di seguito anche fornisce millisecs 3 cifre, ideali per console prefissi di registro:

const timeStrGet = date => {
    const milliSecsStr = date.getMilliseconds().toString().padStart(3, '0') ;
    return `${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;
};

setInterval(() => console.log(timeStrGet(new Date())), 299);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top