4

How can I convert an string like "20150415" to a date with format "2015, April, 15th"? I have read several examples but they all involve a split with "-" or "/", but those don't apply to my case.

Here's my current code:

var d = parseInt(document.getElementById('date').value);
d =  new Date(d[4], d[2] - 1, d[2]);
document.getElementById('date').value = d;  

Any help would be much appreciated.

1
  • Are you really having an integer 20150415 or rather a string "20150415"? edit: Ah, value always returns a string. Commented Apr 16, 2015 at 0:07

4 Answers 4

2

It seems you have a string of the form "YYYYMMDD". To get the individual parts, you just have to extract the substrings. One way would be to use a regular expression:

> "20150415".match(/(\d{4})(\d{2})(\d{2})/)
["20150415", "2015", "04", "15"]

Then you can pass the individual parts (year, month, day) to the Date constructor.

However, note that JavaScript doesn't have built-in support for formatting dates. For that you may want to use a library. See Where can I find documentation on formatting a date in JavaScript?

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a date formatter that takes the string '20150415' and returns the string 'April 4, 2015'. You can adjust the date format to your liking by modifying the last line of DateFormat.toLong.

var DateFormat = {
  months: ['January', 'February', 'March', 'April', 'May', 'June',
           'July', 'August', 'September', 'October', 'November', 'December'],
  toLong: function toLongDate(s) {  // s is a string like '20150415'
    var year = parseInt(s.substring(0, 4), 10),
        month = DateFormat.months[parseInt(s.substring(4, 6), 10) - 1],
        day = parseInt(s.substring(6), 10);
    return month + ' ' + day + ', ' + year;
  }
};

// A small test.
alert(DateFormat.toLong('20150415'));

Note that I am passing the second argument to parseInt to indicate that the number represented by the string is in base 10. If you don't specify base 10, strings starting with the numeral 0 may be parsed as though they were in base 8.

You can read about this in the JavaScript documentation on the Mozilla Developer Network:

If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

2 Comments

Thanks, this worked! May I know what does the 10 mean? such as in (0, 4), 10)
The second argument is the radix of the number. In other words, I'm telling parseInt to use base 10. I have updated my answer with this information. If that satisfies your question, please accept my answer.
0

Try this:

var months = ['January', 'February', 'March', 'April', 'May', 'June',
           'July', 'August', 'September', 'October', 'November', 'December'];
var fmt = function(str) {
  var arr = str.match(/^(\d{4})(\d{2})(\d{2})$/);
  arr.splice(0, 1);
  arr[1] = months[+(arr[1]) - 1];
  return arr.join(", ");
};

alert(fmt('20150412'));//"2015, April, 12"

Comments

0

although the solution of @"Felix Kling" is better, I propose a simple solution:

var d = "20150415";
//Extract 4 first letters and convert to integer, similarly with month and day
var year = parseInt(d.substr(0,4));    
//subtract one since the index of the months begin in zero (january=0)
var month = parseInt(d.substr(4,2))-1;
var day = parseInt(d.substr(6,2));
d =  new Date(year, month, day); // d store expected result

2 Comments

Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. (This post was flagged by at least one user, presumably because they thought an answer without explanation should be deleted.)
Just edit to add an explanation, that will avoid any problems and have a better chance of getting upvotes.

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.