Split the line to get the clock

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

I have a date format, please tell me how to split it so that I can get 12(hours) from this line?

+3
source share
5 answers
var date = '28/05/2011 12:05';
var hrs = date.split(' ')[1].split(':')[0];
+5
source

You can use one call to separate each component with a regular expression:

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

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

+3
source

RegEx Solution:

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

alert(myArray[1]); // 12

Additional Information:

+1
source

While this is a consistent format:

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

pretty easy.

+1
source

when working with dates, it is better to use the dedicated date / time functions:

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

All Articles