0

I need your help

If the code below is able to get the date in my requested format of: dd/mm/yyyy

How do I go about getting the time in a 12hr format ie. 13:53 is 1:53pm

Thank you

<script type="text/javascript">
    function test() {
        var d = new Date(),
            m = d.getMonth() + 1,
            xdate = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/');

        var t = d.format("h:mm ss");

        alert("the date is:" + xdate + "time is:" + t)
    }
</script>
abc123
  • 17,855
  • 7
  • 52
  • 82
John Smith
  • 1,639
  • 11
  • 36
  • 51
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4898574/converting-24-hour-time-to-12-hour-time-w-am-pm-using-javascript – htxryan Aug 27 '13 at 17:57

3 Answers3

1

Demo jsFiddle

JS

var d = new Date();
alert("the date is: " + d.toLocaleDateString() + "time is: " + d.toLocaleTimeString());

Note: these functions aren't exactly cross browser supported

abc123
  • 17,855
  • 7
  • 52
  • 82
0

Use this:

var d = new Date(),
    m = d.getMonth()+1,

    x = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/'),

    y = d.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")

alert(x +" "+ y)

Taken from: How do you display javascript datetime in 12 hour AM/PM format?

Community
  • 1
  • 1
John Smith
  • 1,639
  • 11
  • 36
  • 51
0

It is not that difficult. Try this one out :

JS:

var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}

return function (dt) {
var formatted = '';

if (dt) {
    var hours24 = dt.getHours();
    var hours = ((hours24 + 11) % 12) + 1;
    formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");            
}
return formatted;
}
})();


console.log(formatTime(new Date())); 

Find the working fiddle here : http://jsfiddle.net/rRd2P/1/

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95