Reputation: 7030
This is probably a trivial question, but I'm trying to look for the most efficient way to do this.
I am given a string in this format "20130914" from a servlet and I need to create a javascript date object from it.
From what I know, date object accepts ISO format for strings so I need to append dashes in between my year,month and date like this "2013-09-14"
I could use .splice function to insert dashes in between the year,month and date but I feel like there has to be an easier solution for this trivial question. Or am I overthinking this?
Upvotes: 2
Views: 1960
Reputation: 147343
Rather than parsing a string to create another string to be parsed by the built–in parser, you can get the parts and give them directly to the Date constructor:
let s = '20130914';
// Parse string in YYYYMMDD format to Date object
function parseYMD(s) {
let b = s.match(/\d\d/g);
return new Date(b[0]+b[1], b[2]-1, b[3]);
}
console.log(parseYMD(s).toString());
Upvotes: 0
Reputation: 2294
Using plain and simple JS:
var input = "20130914";
var date = new Date(input.substr(0, 4), input.substr(4, 2) - 1, input.substr(6, 2));
console.log(date.toString());
Upvotes: 1
Reputation: 11805
Because I am in love with regex:
var rawDate = '20130914';
console.log(new Date(rawDate.replace(/(\d{4})(\d{2})(\d{2})/,"$1-$2-$3")));
//Output: Sat Sep 14 2013 12:00:00 GMT+1200 (New Zealand Standard Time)
Upvotes: 3
Reputation: 276276
What you're doing is fine, there is no big problem in writing simple code to do common tasks.
If you find yourself performing a lot of date calculations momentjs is a very small (5kb) library that handles dates just like that.
For example, what you need in moment can be written as:
moment("20130914", "YYYYMMDD");
Upvotes: 3