0

I'm having the issue of converting the following (string) to a date using Javascript:

2nd June 2018

This string is created by another system of which i have no control over other than javascript, in essence i need to convert this string to a date in order to add days on i can display the following example:

2nd June 2018 - 9th June 2018 etc

Unfortunately i have no way around this other than making the conversion,

Any ideas?

Thanks!

  • Isn't this already in date format? What do you want to achieve. provide some samples (example) and your own attempt code – Muhammad Salman May 17 '18 at 10:48
  • Yes please provide some more examples. Is it entered by the user manually or by some other source? – George K May 17 '18 at 10:49
  • It's currently a string, i need to convert it to a date so i can make calculations/add days et – chaoswolf71 May 17 '18 at 10:49
  • 1
    There are a huge number of questions here already on how to parse a timestamp. The answers are the same: use a library with a parser (there are many good ones, many much smaller than moment.js) or write a function to parse your particular format. The second option is maybe 3 lines of code. – RobG May 17 '18 at 13:12

2 Answers2

4

Using moment.js it's easy. Also all your calculations you have to make will be much easier using moment.js...

let d = "2nd June 2018";
let m = moment(d, 'Do MMMM YYYY');
console.log(m.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment-with-locales.min.js"></script>
baao
  • 71,625
  • 17
  • 143
  • 203
1

check this

    console.log(new Date("2nd June 2018".replace(/(\d+)(st|nd|rd|th)/, "$1")));        
Eby Jacob
  • 1,418
  • 1
  • 10
  • 28
  • This might work, but don't do this, you know what they say... "You got a problem? Use regex! Now you got 2 problems". Moment.js is fairly small (16 kb) and can help with dates throughout your project and in case your source changes the way it returns dates, you can quickly adapt to their changes. – Ravenous May 17 '18 at 11:06
  • 1
    16kb is not small – coagmano May 17 '18 at 11:31
  • Parsing of formats other than those noted in ECMA-262 is implementation dependent, hence the usual advice is to not use the built-in parser. – RobG May 17 '18 at 13:20