37

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

My actual format was GMT and I converted it to my bowers time by using the code above.

and I want to change it to 24h time format so I want this date to be changed like: 12/16/2011 15:49:37 and I want to do it in javascript.

Thats what I did

var firstPartOftimeFormat = timeFormat.substring(0,9);
var secondPartOftimeFormat = timeFormat.substring(10,20);

but it does not work when the date format is like: 3/16/2011. but the following part works.

var time = $("#starttime").val();
var hours = Number(secondPartOftimeFormat.match(/^(\d+)/)[1]);
var minutes = Number(secondPartOftimeFormat.match(/:(\d+)/)[1]);
var AMPM = secondPartOftimeFormat.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

Can you suggest other approach?

thanks

4
  • 1
    Various solutions to your problem: stackoverflow.com/questions/1056728/… Commented Mar 12, 2014 at 9:49
  • 1
    Why are you using toLocaleString (which behaves differently for different locales) when you want a specific output format? I'd use a manual formatting here. Commented Mar 12, 2014 at 9:49
  • Do not set any time format javascript Date by default return time in 24hr. Commented Mar 12, 2014 at 9:55
  • Thanks, but my time format was GMT and I converted it to my browers time by var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); and the time is a past time. Commented Mar 12, 2014 at 10:41

15 Answers 15

73

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

Option 1 - Using locales

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

Option 2 - Using options

var options = { hour12: false };
console.log(date.toLocaleString('en-US', options));
Sign up to request clarification or add additional context in comments.

3 Comments

Doesn't seem to work by now for some reason, it still returns time in 12 hours format.
it should be selected answer!
I mistakenly first tried date.toLocaleString(options), which didn't work but didn't fail, but then changed it to date.toLocaleString('en-US', options), which did work.
22

hourCycle: 'h23' is Perfect

Thanks to https://stackoverflow.com/users/12425695/luis-serrano

new Date().toLocaleString('ru-RU', {
    timeZone: 'Europe/Moscow',
    hourCycle: 'h23',
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
});

1 Comment

I think nowadays you use hour12, which is a boolean. So it would be something like: hour12: false, year: "numeric", month: "2-digit", etc etc etc
12

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

Comments

10

To get 24hrs format:

const date = new Date();
console.log(date.toLocaleTimeString([], {
    hourCycle: 'h23',
    hour: '2-digit',
    minute: '2-digit'
}));

Comments

5

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

Comments

4

new Date().toLocaleTimeString('fa-IR', { hour12: false, hour: '2-digit', minute: '2-digit' })

this is how it worked for me!

Comments

3

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

Comments

2

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)

Comments

1

Try this, It's Working fine for me. It gives 24 hrs time format.

let time = new Date(new Date().toLocaleString('en-GB', { timeZone: 'Europe/London' }));

Comments

0

Try this

var d = new Date();
alert(d.getHours());
alert(d.getMinutes());

Comments

0

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>

1 Comment

Thanks, but my time format was GMT and I converted it to my browers time by var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); and the time is a past time. but your solution does not work. since When I apply getHours() in timeFormat = newDate.toLocaleString().getHourse(); it does not work
0
console.log(Utilities.formatDate(new Date(),"GMT+3","dd.MM.yy k:mm:ss"));

try in format k:m:s insted of hh:mm:ss to

Utilities.formatDate

Tutorial Class SimpleDateFormat

Comments

0

const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm"); console.log(number);

Comments

0

This worked for me. de-DE can be replaced with any language string like us-GB , nl-NL, etc.

function showTime() {
    const date = new Date();
    let time = date.toLocaleTimeString('de-DE', {
        hour12: false,
        hour: '2-digit',
        minute:'2-digit',
        second:'2-digit'
    });
    document.getElementById("MyClockDisplay").innerText = time;
    setTimeout(showTime, 1000);
}

showTime();

Comments

0

I find the below being the most accurate.

const currentTime = new Date().toLocaleTimeString([], { 
    hour: '2-digit',
     minute: '2-digit' 
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.