-2

I have a date string and I want to convert it into a date object using date(). It's doing so but the problem is, date() processes any date as 'MM-dd-yyyy'.

I tried following code:

var myDate = '09-06-2017'; //which is a string and is in 'dd-MM-yyyy' format from my perspective

var selectedDate = new Date(myDate);
$scope.minDate = $filter('date')(selectedDate, 'yyyy/MM/dd');

console.log(selectedDate);
console.log($scope.minDate);

It will process this date as 06-09-2017 and if I pass '13-06-2017'(i.e. any value greater than 12) then it will throw 'Invalid Date' in console.

So I'm looking for a solution by which I can tell date() to process the passed string in a specific format.

Thank You.

TheCleverIdiot
  • 412
  • 4
  • 19
  • Use [Moment.js](https://momentjs.com/) – Liam Sep 01 '17 at 08:53
  • You could give it duplicate flag if you feel so rather than downvoting. – TheCleverIdiot Sep 01 '17 at 09:01
  • You could do some research before asking a question that's already been asked, several times. The downvote prompt states *"**This question does not show any research effort**; it is unclear or not useful"*. – Liam Sep 01 '17 at 09:31
  • OHH.. research.. that's what I think I was doing from the 3 or 4 hours before I asked here a question. And anyhow, the question you guys mentioned of which my question seems to be duplicate, has not the answer I'm looking for. So thank you very much for your kind responses. – TheCleverIdiot Sep 02 '17 at 05:12

1 Answers1

0

With out using any libraries you can split the date in to parts and pass them to Date(year, month, day) constructor.

var myDate = '09-06-2017';
var myDateParts = myDate.split('-');
var selectedDate = new Date(myDateParts[2], myDateParts[0] - 1, myDateParts[1]);

console.log(selectedDate);
Jurij Jazdanov
  • 1,248
  • 8
  • 11