Mehmet Akif Güzey
Mehmet Akif Güzey

Reputation: 367

Splitting string which includes( / and : ) into an array in Javascript

I have a string that includes date and time together. I need all of them seperated in some cases. My string is like this : 28/08/2015 11:37:47

There are some solutions in there but they do not fix my problem

var date = "12/15/2009";
var parts = date.split("/");
alert(parts[0]); // 12
alert(parts[1]); // 15
alert(parts[2]); // 2009

This is similar thing but as I said above, I need to split all of them.

Thank you for your help

Upvotes: 1

Views: 206

Answers (3)

Tschallacka
Tschallacka

Reputation: 28722

If you always have that datetime format I'd suggest a simple regex

"28/08/2015 11:37:47".split(/\/|\s|:/)

This splits it on a / a space and the colon

and will return

 ["28", "08", "2015", "11", "37", "47"]

Edit as per question asked in comment

function parse() {
  /** INPUT FORMAT NEEDS TO BE DAY/MONTH/YEAR in numbers for this to work **/
  var datetime= document.getElementById("datetime").value;
  var time = document.getElementById("time").value;
  var output = document.getElementById("output")
  var datetimearr = datetime.split(/\/|\s|:/);
  var timearr = time.split(/:/);
  var date = new Date(datetimearr[2],datetimearr[1]-1,datetimearr[0],datetimearr[3],datetimearr[4],datetimearr[5]);
  date.setHours(date.getHours()+(parseInt(timearr[0])));//parseInt needed otherwise it will default to string concatenation
  date.setMinutes(date.getMinutes()+(parseInt(timearr[1])));
  date.setSeconds(date.getSeconds()+(parseInt(timearr[2])));
  output.value = date.toString();
}
Date time: <input type="text" value="28/08/2015 11:37:47" id="datetime"><BR/>
Time to add: <input type="text" value="11:37:47" id="time"><input type="button" value="calculate!" onclick="parse()"><BR/>
<textarea  id="output" placeholder="Output comes here" style="width:400px;height:100px;"></textarea>

Upvotes: 2

Flash Thunder
Flash Thunder

Reputation: 12036

You can simply convert the string to date by:

var datestr = "12/15/2009 11:33:44";
var date = new Date(datestr);

And now access the values by those functions:

date.getDate(); //  -> 15
date.getMonth(); //  -> 12
date.getFullYear(); //  -> 2009
date.getHours(); //  -> 11
date.getMinutes(); //  -> 33
date.getSeconds(); //  -> 44

working js fiddle example here

EDIT: Had to fix example because document.write didn't work correctly on Fiddle.

Upvotes: 1

iplus26
iplus26

Reputation: 2637

You can use regular expressions.

var str = '28/08/2015 11:37:47';

console.log(str.split(/[\/:\s]/));

Upvotes: 2

Related Questions