Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split date string with dashes

Tags:

jquery

date

split

I have a date value in this format: 20160810

I need to split it into a proper date format like so: 2016-08-10

In jquery, how would I achieve this? I can't use split() because it has to have a delimiter to reference, so I'm not sure if there's a function that can split based on the number of characters.

like image 989
Eckstein Avatar asked Aug 11 '16 05:08

Eckstein


4 Answers

Use String#replace method

var res = '20160810'.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')

console.log(res);

Regex explanation here.

Regular expression visualization


Or with String#slice method

var str = '20160810';

var res = str.slice(0, 4) + '-' + str.slice(4,6) + '-' + str.slice(-2);

console.log(res);
like image 98
Pranav C Balan Avatar answered Oct 17 '22 22:10

Pranav C Balan


Good Morning!

Maybe you try to use the substr() function. This functions cuts an substring out of your string, based on an beginning and ending charindex:

var string = "20160810";
var date = string.substr(0,3)+"-"+string.substr(4,5)+"-"+string.substr(6,7);

This is also possible with an regex:

var string = "20160810";
var date = string.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); //2016-08-10

In the second example you use the capturing groups to capture three decimals of different lengths and replace them with themselves separated with an -.

I hope I could help!

like image 20
Otterbein Avatar answered Oct 17 '22 22:10

Otterbein


If you're not into doing things with RegExp:

var dateArray = '20160810'.split('')
var year = dateArray.slice(0,4).join('')
var month = dateArray.slice(4,6).join('')
var day = dateArray.slice(6).join('')
console.log([year, month, day].join('-'))
like image 35
jakee Avatar answered Oct 18 '22 00:10

jakee


You could also use momentjs:

> moment("20160810", "YYYYMMDD").format("YYYY-MM-DD")
'2016-08-10'
like image 30
Nehal J Wani Avatar answered Oct 17 '22 22:10

Nehal J Wani