admin管理员组

文章数量:1320624

new Date(timestamp).getHours();
new Date(timestamp).getMinutes();

I have a timestamp, i convert it to h/m, ex.00:00

how can I convert it to the format with 2 digit style, what I have now is 0:0

new Date(timestamp).getHours();
new Date(timestamp).getMinutes();

I have a timestamp, i convert it to h/m, ex.00:00

how can I convert it to the format with 2 digit style, what I have now is 0:0

Share Improve this question asked Feb 12, 2014 at 13:08 BenBen 2,5648 gold badges39 silver badges63 bronze badges 1
  • If you don't like reinventing wheels, consider sprintf or moment.js. – georg Commented Feb 12, 2014 at 13:22
Add a ment  | 

4 Answers 4

Reset to default 4

You'll have to pad your digits.

Try this:

var h = new Date(timestamp).getHours();
var m = new Date(timestamp).getMinutes();

h = (h<10) ? '0' + h : h;
m = (m<10) ? '0' + m : m;

var output = h + ':' + m;

Or place the padding in a function:

function pad(val){
     return (val<10) ? '0' + val : val;
}

And use that like this:

var h = new Date(timestamp).getHours();
var m = new Date(timestamp).getMinutes();
var output = pad(h) + ':' + pad(m);

A solution that works without creating a function, or having too many lines of code and works with locale is to use toTimeString(). See: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString

let ts = new Date('August 19, 1975 23:15:01').toTimeString();
console.log(ts);
// output: 23:15:01 GMT+0200 (CEST)

let hhmm = ts.toTimeString().slice(3, 9);
console.log(hhmm);
// output: 15:01

Here is your one-liner:

new Date(timestamp).toTimeString().slice(3, 9);

You can try with:

var date    = new Date(timestamp),
    hours   = date.getHours(),
    minutes = date.getMinutes();

var output  = ("0" + hours).slice(-2) + ':' + ("0" + minutes).slice(-2);

I always prefer to have little helper around for these tasks. Like this function - padZero()

var h = padZero(new Date(timestamp).getHours() );
var m = padZero(new Date(timestamp).getMinutes() );

function padZero(n) {
  if (n < 10) return '0' + n;
  return n;
}

本文标签: javascript convert timestamp to 2 digit style of hoursminutesStack Overflow