-4

I have string in below format:

 09Aug

 23Aug

 Sept27

 06Sep

How can I convert these Strings into proper date format? As I am not getting any year in above string so as a year I will consider current year I did a lot of googles but couldn't found anything?

JSDBroughton
  • 3,966
  • 4
  • 32
  • 52
Saurabh Garg
  • 199
  • 7
  • 22

2 Answers2

0

You'd have to separate the date and month, keep an array of valid months, then pass those numbers into new Date, something like

function parseDate(d) {
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']
  var date   = +d.replace(/\D/g,'');
  var mon    = months.indexOf( d.replace(/\d/g,'') );
  
  return new Date(2017, mon, date);
}

console.log( parseDate("09Aug") );
console.log( parseDate("23Aug") );
console.log( parseDate("Sept27") ); // why four letters ?

(Note: dates are "local" in JS, so parsing them could result in differences, use UTC if important)

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

1) Concatenate current year to the string as :

var str1 = '09 Aug';
var str2 = ' '+(new Date()).getFullYear();
var res = str1.concat(str2);//outputs 09 Aug2017
new Date(res);//outputs Wed Aug 09 2017 00:00:00 GMT-0400 (Eastern Daylight Time)