Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting date in Javascript

Tags:

javascript

var date = "1st December,2016"

How can I split this string to get date,month and year? I am doing date.split(" ",1) then I am getting output as "1st". Now how to get December and 2016?

like image 993
Abhijeet Avatar asked Oct 25 '25 05:10

Abhijeet


1 Answers

If you could make sure that your string always has that format, the simplest way is to use 2 split command:

var date = "1st December,2016";

var arr1 = date.split(' ');
var arr2 = arr1[1].split(',');

console.log('date: ', arr1[0]);
console.log('month: ', arr2[0]);
console.log('year: ', arr2[1]);

Update: I just realize split could be used with Regex, so you could use this code too:

var date = '1st December,2016';
var arr = date.split(/ |,/);

console.log('date: ', arr[0]);
console.log('month: ', arr[1]);
console.log('year: ', arr[2]);
like image 183
kkkkkkk Avatar answered Oct 27 '25 17:10

kkkkkkk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!