2016-07-10 13 views
1

Zeit habe ich einfach Code für 12hr FormatAM/PM mit Javascript

// This function gets the current time and injects it into the DOM 
     function updateClock() { 
       // Gets the current time 
       var now = new Date(); 

       // Get the hours, minutes and seconds from the current time 
       var hours = now.getHours(); 
       var minutes = now.getMinutes(); 
       var seconds = now.getSeconds(); 


       // Format hours, minutes and seconds 
       if (hours > 12) { 
        hours = hours - 12; 
       } 
       if (minutes < 10) { 
        minutes = "0" + minutes; 
       } 
       if (seconds < 10) { 
        seconds = "0" + seconds; 
       } 

       // Gets the element we want to inject the clock into 
       var elem = document.getElementById('clock'); 

       // Sets the elements inner HTML value to our clock data 
       elem.innerHTML = hours + ':' + minutes + ':' + seconds ; 
      } 

Ich möchte hinzufügen, AM/PM mir bitte helfen Vielen Dank im Voraus Im gerade Javascript

+1

Hier ist ein Hinweis: Wenn Sie 12 Stunden subtrahieren hatte, dann PM es ist. Sonst ist es AM. –

Antwort

1

Try this Anfänger Hinzufügen. ..

var ampm = hours >= 12 ? 'pm' : 'am'; 

dann

elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + ampm; 
+0

Es funktioniert jetzt Vielen Dank –

+0

froh, Hilfe zu sein :) – Sankar

3

Nach Ihrem eigenen Code editting:

 // Get the hours, minutes and seconds from the current time 
     var hours = now.getHours(); 
     var minutes = now.getMinutes(); 
     var seconds = now.getSeconds(); 
     var amOrPm = 'AM'; 

     // Format hours, minutes and seconds 
     if (hours > 12) { 
      amOrPm = 'PM'; 
      hours = hours - 12; 
     } 
     if (minutes < 10) { 
      minutes = "0" + minutes; 
     } 
     if (seconds < 10) { 
      seconds = "0" + seconds; 
     } 

     // Gets the element we want to inject the clock into 
     var elem = document.getElementById('clock'); 

     // Sets the elements inner HTML value to our clock data 
     elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + amOrPm; 
0

Ich weiß nicht, ob Sie es selbst codieren wollen, aber es ist eine wirklich, wirklich große Bibliothek, die man sich vorstellen kann alles mit Datum Sachen behandelt.

Nur Kasse momentjs. Es ist eine einfache AF lib um Daten zu transformieren (auch in pm/am).

Wenn Sie Fragen haben :) nur einen Kommentar ...