change time format to 24 hours in javascript

前端 未结 7 935
春和景丽
春和景丽 2020-12-15 23:12

I have a time format like: 12/16/2011 3:49:37 PM and I got this format by:

var newDate = new Date(timeFromat);
timeFormat = newDate.toLocaleString();
         


        
相关标签:
7条回答
  • 2020-12-15 23:37

    You can use the below code to get 24hrs format

    new Date("3/16/2011 3:49:37 PM").getHours() // 15
    new Date("3/16/2011 3:49:37 PM").getMinutes() // 49
    
    0 讨论(0)
  • 2020-12-15 23:41

    Try this, Its Perfectly Working fine for me. It gives 24 hrs time format

    var Date= new Date();
    
    var TimeFormat= date.toLocaleString('en-GB');
    

    Your answer will be Fri Dec 14 2018 18:00:00 GMT+0530 (India Standard Time)

    0 讨论(0)
  • 2020-12-15 23:42

    Using some resources
    Date/toLocaleDateStringMDN
    Date/toLocaleTimeStringMDN

    const lang = navigator.language || navigator.languages[0];
    const date = new Date();
    const date_locale = date.toLocaleDateString(lang, {
      day: 'numeric',
      month: 'short',
      year: 'numeric'
    });
    const time_locale = date.toLocaleTimeString(lang);
    
    const formatted = `${date_locale} ${time_locale}`;
    console.log(formatted)

    above we deduce the current language from the Window's Navigator object.
    In case lang ends up being undefined it's perfectly fine, defaults will be used.

    To force a desired format, you can manually set lang to i.e: 'en-US', 'eu', 'en-GB', 'de-DE', 'hr-HR' etc...

    Here's an example for time:

    const date = new Date();
    console.log(date.toLocaleTimeString('en-US')) // 12h
    console.log(date.toLocaleTimeString('en-GB')) // 24h
    console.log(date.toLocaleTimeString())        // Default

    0 讨论(0)
  • 2020-12-15 23:44

    Try this function

    <script type="text/javascript">
        <!--
        function displayTime() {
            var currentDate = new Date();
            var currentHour = currentDate.getHours();
            var currentMinute = currentDate.getMinutes();
            var currentSecond = currentDate.getSeconds();
            document.getElementById('timeDiv').innerHTML = 'Hour: ' + currentHour + ' Minute: ' + currentMinute + ' Second: ' + currentSecond;
        }
    
        window.onload = function() {
            window.setInterval('displayTime()', 1000);
        }
        // -->
    </script>
    
    0 讨论(0)
  • 2020-12-15 23:47

    try this:

    // British English uses day-month-year order and 24-hour time without AM/PM
    console.log(date.toLocaleString('en-GB'));
    // → "20/12/2012 03:00:00"
    

    reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

    0 讨论(0)
  • 2020-12-15 23:53

    Try this

    var d = new Date();
    alert(d.getHours());
    alert(d.getMinutes());
    
    0 讨论(0)
提交回复
热议问题