1

I'm working on a project where I need to get the hours and minutes alone without the semicolon (:) separating them, and represent them in a variable, myTime, as a 4-digit number. Here is my code:

var now = new Date();
var time = now.toString().substr(16,5)
Tomas Langkaas
  • 4,551
  • 2
  • 19
  • 34
  • 2
    `now.getHours() + '' + now.getMinutes()` although if you want it as an actual *number* (which seems weird) you'd have to convert it to a number. And if you want two-digit numbers, better off just formatting it, like with `toLocaleString` or the like. – Dave Newton Dec 27 '16 at 19:55
  • Easy solution is to use library momentjs. with that you can write moment().format('HHmm'); and you should get time properly formated – Piotr Pasieka Dec 27 '16 at 19:58

2 Answers2

4

Use the .getHours() and .getMinutes() methods of Date objects to get these numbers. To get a 4-digit number representation (as a zero-padded string), concatenate and zero-pad as necessary with ('0000' + (hours * 100 + minutes)).slice(-4)as demonstrated below:

var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var myTime = ('0000' + (hours * 100 + minutes)).slice(-4);
//note that myTime is a zero-padded string of length 4

console.log(now.toString(), hours, minutes, myTime);
Tomas Langkaas
  • 4,551
  • 2
  • 19
  • 34
1

To get Hours or Minutes from a datetime use the associated functions myDate.getHours() or myDate.getMinutes()

Edit: you probably don't want military time so adding 12 hour conversion...

var mt = getHoursMinutesSeconds(new Date());
alert(mt);

    function getHoursMinutesSeconds(date) {
        var h = date.getHours();            
        h = ((h + 11) % 12 + 1);
        var m = date.getMinutes();
        var myTime =  addZero(h) + addZero(m);
        return myTime;
        }


function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}
pizzaslice
  • 478
  • 2
  • 8