Mou
Mou

Reputation: 16282

How to convert Hour to 12 HRS / 24 HRS Format with javascript

i convert Hour to 12 HRS / 24 HRS Format this way in c# but not being able to do the same in javascript.

my c# code for formatting 12 HRS / 24 HRS Format as below

for (int i = 0; i <= 15; i++)
{
    strHrs.Add((i == 0 ? "00" : Convert.ToDateTime(TimeSpan.FromHours(i).ToString()).ToString("hh")),
        (i == 0 ? "00" : Convert.ToDateTime(TimeSpan.FromHours(i).ToString()).ToString("HH")));
}

i got a js code which looks fine

var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = H < 12 ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;

i have to show 12 hrs format in dropdown text but have to show 24 hrs format in dropdown value.
but how to apply in my case not very sure. so any help would be appreciated. thanks

EDIT

        function convertDateTo12Hrs(timeStr, is24) {
            if (is24) {
                var BigHrs = timeStr.toString().length == 1 ? "0" + timeStr : timeStr;
                return BigHrs; // return if is24 true
            }
            var h = "" + (+timeStr > 12 ? timeStr - 12 : timeStr);
            return h.length == 1 ? "0" + h : h;
        }

Calling

convert("2", true); // "02"
convert("18", false); // "06"

Upvotes: 2

Views: 152

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

Base on your comment on my post, you could just create a function which would return both.

function convert(timeStr, is24) {
    if (is24) return timeStr; // return if is24 true
    var h = "" + (+timeStr  > 12 ? timeStr - 12 : timeStr);
    return h.length == 1 ? "0" + h : h;
}

Now you can call it like

convert("18", true); // "18"
convert("18", false); // "06"

Upvotes: 1

Related Questions