Come si visualizza il datetime JavaScript in formato 12 ore AM / PM?


306

Come si visualizza un oggetto datetime JavaScript nel formato 12 ore (AM / PM)?


3
Non perdere tempo stackoverflow.com/a/17538193/3541385 funziona ...
— Ritesh

2
@Ritesh WARNING: toLocaleTimeString() may behave differently based on region / location.Misura due volte, taglia una volta.
— Carrello abbandonato

@AbandonedCart è davvero un detto?
— gilbert-v

1
@ gilbert-v One should double-check one's measurements for accuracy before cutting a piece of wood; otherwise it may be necessary to cut again, wasting time and material.Questa domanda è probabilmente meglio posta su Google, però.
— Carrello abbandonato

Non mi abituerò mai a quanto dannatamente contorto stia cercando di lavorare con date semplici in JavaScript. 😠
— ashleedawg

Risposte:


545

function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

console.log(formatAMPM(new Date));


3
Inoltre hai dichiarato due volte la variabile "hours" ma hai reso "strTime" un global accidentale. Non è estremamente elegante ma questa sembra essere la tecnica corretta usando metodi nativi.
— Jon z,

Ciao, puoi lamentarmi con me cosa stai facendo con questo: minuti = minuti <10? '0' + minuti: minuti;
— Balz,

2
@Balz Se i minuti sono meno di 10 (es. 16:04), quell'istruzione aggiunge la stringa "0" in modo che l'output formattato sia "16:04" invece di "16:04". Si noti che nel processo, i minuti cambiano da un numero a una stringa.
— Caleb Bell,

7
Preferisco questo minutes = ('0'+minutes).slice(-2);piuttosto che minutes = minutes < 10 ? '0'+minutes : minutes;
— Vignesh,

1
La soluzione @Vignesh per i minuti è migliore perché se stai facendo quello suggerito 21:00:00 diventa 9: 000. Vignesh ti dà i minuti corretti come: 00. Se dovessi utilizzare la soluzione di cui sopra, dovresti tenere conto anche di 00. (minuti> 0 && minuti <10)? '0' + minuti: minuti;
— Robbie Smith,

201

Se vuoi solo mostrare le ore allora ...

var time = new Date();
console.log(
  time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);  

Uscita: 7 AM

Se desideri mostrare anche i minuti, allora ...

var time = new Date();
console.log(
  time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
);

Uscita: 7:23 AM


Che dire di ora, minuti e AM / PM?
— Reutsey,

3
toLocaleStringè supportato solo su IE11 +.
— Neolisk,

A partire da febbraio 2018 funziona perfettamente su Chrome Neolisk - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
— lfender6445

dovrebbe restituire 07:23, IMO
— Humble Dolt,

@HumbleDolt Potresti essere confuso 'numeric'con '2-digit'.
— hon2a

55

Puoi anche considerare l'utilizzo di qualcosa come date.js :

<html>
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>

<script>
   (function ()
   {
      document.write(new Date().toString("hh:mm tt"));
   })();
</script>
</html>


45

Ecco un modo usando regex:

console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
console.log(new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))

Questo crea 3 gruppi corrispondenti:

  • ([\d]+:[\d]{2}) - Ora: minuti
  • (:[\d]{2}) - Secondi
  • (.*) - lo spazio e il periodo (Periodo è il nome ufficiale per AM / PM)

Quindi visualizza il 1 ° e il 3 ° gruppo.

ATTENZIONE: toLocaleTimeString () potrebbe comportarsi diversamente in base alla regione / posizione.


3
Le persone non usano abbastanza Regex. Questo ha funzionato per me senza aggiungere i suggerimenti della libreria jquery / microsoftajax sopra.
— uadrive,

Quale sarebbe la regex avere uno zero finale all'inizio dell'ora se fosse una singola cifra. Di 'nel tuo primo esempio di 20:12 che sarebbero le 08:12?
— RADXack,

1
@ 404 è lo stesso, ([\d]+:[\d]{2})è la parte che ci interessa. Usa i due punti (:) come separatore e vediamo che la prima parte è [\d]+. Il plus significa uno o più. Quindi sta cercando una o più cifre (incluso lo zero. Se dovessi garantire che ci sia uno zero, lo sarebbe (0[\d]:[\d]{2}). Questo ora legge, cerca 0 più un'altra cifra, poi due punti, quindi il resto.
— Steve Tauber,

1
console.log (nuova data (). toLocaleTimeString (). replace (/ ([\ d] +: [\ d] {2}) (: [\ d] {2}) (. *) /, "$ 1 $ 3 ")); Per ottenere l'ora corrente
— mujaffars

35

Se non hai bisogno di stampare am / pm, ho trovato quanto segue carino e conciso:

var now = new Date();
var hours = now.getHours() % 12 || 12;  // 12h instead of 24h, with 12 instead of 0. 

Questo si basa sulla risposta di @ bbrame.


3
@koolinc per mezzanotte mostra 12. Non sono sicuro di cos'altro sarebbe il comportamento desiderato.
— rattray il

Sono corretto. Nel mio paese viene utilizzato l'orologio a 24 ore, quindi non ho familiarità con l'orologio a 12 ore. Effettivamente la mezzanotte è alle 12:00.
— KooiInc,

16

Per quanto ne so, il modo migliore per ottenerlo senza estensioni e codifiche complesse è il seguente:

     date.toLocaleString([], { hour12: true});

Formato Javascript AM / PM

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to display the date and time as a string.</p>

    <button onclick="myFunction()">Try it</button>
    <button onclick="fullDateTime()">Try it2</button>
    <p id="demo"></p>
    <p id="demo2"></p>
    <script>
        function myFunction() {
            var d = new Date();
            var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });
            document.getElementById("demo").innerHTML = n;
        }
        function fullDateTime() {
            var d = new Date();          
            var n = d.toLocaleString([], { hour12: true});
            document.getElementById("demo2").innerHTML = n;
        }
    </script>
</body>
</html>

Ho trovato questo controllando questa domanda.

Come posso usare .toLocaleTimeString () senza visualizzare i secondi?



12

Di seguito trovi la soluzione

var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return   d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;

Dovrebbe essere minore o uguale a per il calcolo dell'ora, altrimenti mezzogiorno viene visualizzato come 0. Quindi: var hour = (d.getHours () <= 12). Ha ancora problemi con la mezzanotte, quindi devi controllare se zero quindi impostare anche su 12.
— Ryan,

11

uso dateObj.toLocaleString([locales[, options]])

Opzione 1 : utilizzo delle versioni locali

var date = new Date();
console.log(date.toLocaleString('en-US'));

Opzione 2 : utilizzo delle opzioni

var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));

Nota: supportato su tutti i browser tranne Safari Atm



9

Breve RegExp per en-US:

var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"

questo non funziona con gli ultimi browser Safari e Firefox, il tempo utilizza ancora il formato 24 ore
— euther

1
le risposte diventano obsolete col passare del tempo. Sentiti libero di modificare e aggiornare!
— Geo

Questo in realtà farà sembrare la stringa 1:54 PM CDT. Per rimuovere l' CDTalter regex al seguente .replace(/:\d+ |\CDT/g, ' '). Anche se, CDT è solo il mio fuso orario. Se hai un fuso orario diverso suppongo che dovresti passare a quel codice di zona.
— sadmic Microwave,

L'output di toLocaleTimeString dipende dall'implementazione, quindi non è lo stesso formato affidabile ovunque.
— RobG

9

Nei browser moderni, utilizzare Intl.DateTimeFormate forzare il formato 12 ore con le opzioni:

    let now = new Date();

    new Intl.DateTimeFormat('default',
        {
            hour12: true,
            hour: 'numeric',
            minute: 'numeric'
        }).format(now);

    // 6:30 AM

L'utilizzo defaultrispetterà le impostazioni internazionali predefinite del browser se aggiungi più opzioni, ma genererà comunque il formato 12 ore.


per utilizzarlo, assegnare la nuova stringa a una variabile, ad esempio: let result = new Intl.DateTi .... alert (risultato);
— Scot Nery,

7

Usa Moment.js per questo

Utilizzare i codici seguenti in JavaScript quando si utilizza moment.js

H, HH       24 hour time
h, or hh    12 hour time (use in conjunction with a or A)

Il format()metodo restituisce la data nel formato specifico.

moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)


4

Ho fonte è qui che lavorando bene.

var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/


var d       = new Date();
var hour    = d.getHours();  /* Returns the hour (from 0-23) */
var minutes     = d.getMinutes();  /* Returns the minutes (from 0-59) */
var result  = hour;
var ext     = '';

if(date_format == '12'){
    if(hour > 12){
        ext = 'PM';
        hour = (hour - 12);

        if(hour < 10){
            result = "0" + hour;
        }else if(hour == 12){
            hour = "00";
            ext = 'AM';
        }
    }
    else if(hour < 12){
        result = ((hour < 10) ? "0" + hour : hour);
        ext = 'AM';
    }else if(hour == 12){
        ext = 'PM';
    }
}

if(minutes < 10){
    minutes = "0" + minutes; 
}

result = result + ":" + minutes + ' ' + ext; 

console.log(result);

ed esempio di plunker qui


4
<script>
var todayDate = new Date();
var getTodayDate = todayDate.getDate();
var getTodayMonth =  todayDate.getMonth()+1;
var getTodayFullYear = todayDate.getFullYear();
var getCurrentHours = todayDate.getHours();
var getCurrentMinutes = todayDate.getMinutes();
var getCurrentAmPm = getCurrentHours >= 12 ? 'PM' : 'AM';
getCurrentHours = getCurrentHours % 12;
getCurrentHours = getCurrentHours ? getCurrentHours : 12; 
getCurrentMinutes = getCurrentMinutes < 10 ? '0'+getCurrentMinutes : getCurrentMinutes;
var getCurrentDateTime = getTodayDate + '-' + getTodayMonth + '-' + getTodayFullYear + ' ' + getCurrentHours + ':' + getCurrentMinutes + ' ' + getCurrentAmPm;
alert(getCurrentDateTime);
</script>

2
Ottenere il modulo dell'ora con 12 è eccellente! Questo impedisce di ottenere zero quando sono le 12:00 o le 12:00
— Lynnell Emmanuel Neri,

3

Ecco un altro modo semplice e molto efficace:

        var d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->

1

puoi determinare am o pm con questo semplice codice

var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';

0

var d = new Date();
var hours = d.getHours() % 12;
  hours = hours ? hours : 12;
    var test = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(d.getMonth() + 1)] + " " + 
    ("00" + d.getDate()).slice(-2) + " " + 
    d.getFullYear() + " " + 
    ("00" + hours).slice(-2) + ":" + 
    ("00" + d.getMinutes()).slice(-2) + ":" + 
    ("00" + d.getSeconds()).slice(-2) + ' ' + (d.getHours() >= 12 ? 'PM' : 'AM'); 
    
document.getElementById("demo").innerHTML = test;
<p id="demo" ></p>


0
<h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>



<script>
            var AM_or_PM = "AM";

            function startTime(){

                var today = new Date();
                var h = today.getHours();
                var m = today.getMinutes();
                var s = today.getSeconds();

                h = twelve_hour_time(h);
                m = checkTime(m);
                s = checkTime(s);



                document.getElementById('clock_display').innerHTML =
                    h + ":" + m + ":" + s +" "+AM_or_PM;
                var t = setTimeout(startTime, 1000);

            }

            function checkTime(i){

                if(i < 10){
                    i = "0" + i;// add zero in front of numbers < 10
                }
                return i;
            }

            // CONVERT TO 12 HOUR TIME. SET AM OR PM
            function twelve_hour_time(h){

                if(h > 12){
                    h = h - 12;
                    AM_or_PM = " PM";
                }
                return h;

            }

            startTime();

        </script>

0
function getDateTime() {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();

  if (month.toString().length == 1) {
    month = '0' + month;
  }
  if (day.toString().length == 1) {
    day = '0' + day;
  }

  var hours = now.getHours();
  var minutes = now.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var timewithampm = hours + ':' + minutes + ' ' + ampm;

  var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
  return dateTime;
}

0

Ecco la mia soluzione

function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
    strampm= "PM";
} else {
    strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
    hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}

function checkTimeAddZero(i) {
if (i < 10) {
    i = "0" + i
}
return i;
}

-1

O semplicemente fai il seguente codice:

    <script>
        time = function() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            document.getElementById('txt_clock').innerHTML = h + ":" + m + ":" + s;     
            var t = setTimeout(function(){time()}, 0);
        }

        time2 = function() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            m = checkTime(m);
            s = checkTime(s);
            if (h>12) {
                document.getElementById('txt_clock_stan').innerHTML = h-12 + ":" + m + ":" + s;
            }               
            var t = setTimeout(function(){time2()}, 0);
        }

        time3 = function() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            if (h>12) {
                document.getElementById('hour_line').style.width = h-12 + 'em'; 
            }
            document.getElementById('minute_line').style.width = m + 'em';  
            document.getElementById('second_line').style.width = s + 'em';  
            var t = setTimeout(function(){time3()}, 0);
        }

        checkTime = function(i) {
            if (i<10) {i = "0" + i};  // add zero in front of numbers < 10
            return i;
        }           
    </script>


-1

Un'implementazione breve e dolce:

// returns date object in 12hr (AM/PM) format
var formatAMPM = function formatAMPM(d) {
    var h = d.getHours();
    return (h % 12 || 12)
        + ':' + d.getMinutes().toString().padStart(2, '0')
        + ' ' + (h < 12 ? 'A' : 'P') + 'M';
};

-1

prova questo

      var date = new Date();
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var seconds = date.getSeconds();
      var ampm = hours >= 12 ? "pm" : "am";

Questo non è corretto Le ore potrebbero essere superiori a 12.
— Utsav T

Alle 12:00 il var ampm sarà "pm". Quindi, dalle 12:00 alle 23:00, le ore da 12 a 23 memorizzeranno il valore "pm" e, per altri, var ampm memorizzerà il valore "am". Spero che tu capisca.
— Md Juyel Rana,

Ciao Juyel! In effetti, quando le ore sono maggiori di 12, il valore sarebbe PM. Ma la domanda è "Come si visualizza datetime JavaScript in formato 12 ore AM / PM?" - devi aiutare OP a convertire tutto il tempo nel formato AM / PM. Ad esempio, le 14:30 sarebbero le 14:30.
— Utsav T
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.