Reputation: 442
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?
Upvotes: 4
Views: 64380
Reputation: 7738
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]);
Upvotes: 8
Reputation: 41
var date = "1st December,2016";
var dataArray = date.split(/[ ,]/);
console.log('Day:' + dataArray[0]);
console.log('Month:' + dataArray[1]);
console.log('Year:' + dataArray[2]);
Upvotes: 0
Reputation: 1136
Use Regular Expression for that,
function ShowDateParts()
{
var regex =/\s|,/g;
fullDate = "1st December,2016";
var dateParts =fullDate.split(/[\s|,]/g);
alert("date : "+ dateParts[0] + " Month : " +dateParts[01] + " Year : " + dateParts[02]);
}
Upvotes: 3
Reputation: 5466
I would create a date object out of my string value and use is to get all values.
Example Snippet:
var date = "1st December,2016";
//reftor to valid date
var validDate = date.replace(/(st)/, '');
//create date object
var dateObj = new Date(validDate);
//get any value you need
console.log(dateObj.getDate());
console.log(dateObj.getMonth());
Update:
Snippet to get intended output: (get month as string)
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = "1st December,2016";
//reftor to valid date
var validDate = date.replace(/(st)/, '');
//create date object
var dateObj = new Date(validDate);
//get any value you need
console.log(dateObj.getDate());
console.log(monthNames[dateObj.getMonth()]);
console.log(dateObj.getFullYear());
Upvotes: 0
Reputation: 10174
Instead of
date.split(" ",1)
Just use
var dateparts = date.split(" ");
And then access each part as an array element.
var day=dateparts [0];
var month=dateparts [1].slice(0, -1);
var year=dateparts [2];
Upvotes: 0