2

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?

1
  • I think, as you mentioned, you have to parse the string yourself. like.. var year = mydatestr.substring(0,4) Commented May 23, 2013 at 2:28

4 Answers 4

3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I'll be handling a lot of date calculations. Thanks for recommending a great library.
3

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) 

Comments

1

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());

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.