开发者

Split string to get hours

var date = '28/05/2011 12:05';
var elem = date.split('');
hours = elem[0]开发者_StackOverflow;

I have the above date format, please tell me how to split this, so that I can obtain 12 (hours) from this string?


var date = '28/05/2011 12:05';
var hrs = date.split(' ')[1].split(':')[0];


You can use a single call to split each component using a regular expression:

var date = '28/05/2011 12:05';
var elem = date.split(/[/ :]/);
alert(elem[3]); //-> 12

Working example: http://jsfiddle.net/gZ9c7/


A RegEx solution:

var myRe = /([0-9]+):[0-9]+$/i;
var myArray = myRe.exec("28/05/2011 12:05");

alert(myArray[1]); // 12

Some additional info:

  • Working code sample here.
  • About RegEx in JS.


As long as it's a consistent format:

var hours = date.split(' ')[1].split(':')[0]

is pretty easy.


when working with Dates it's better to use dedicated date/time functions:

var date = '28/05/2011 12:05';
var ms = Date.parse(date)
alert(new Date(ms).getHours())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜