2

I would like to get "2016-10-01" when I use moment("2016-09-31"). However, When I try it, I get INVALIDA DATE message.

Is it possible?

Amparo
  • 784
  • 1
  • 4
  • 21
  • Well, the lib behaves the way it behaves. You may either ask developers about implementing such a feature or implement your own helper and call it before colling `moment`. – YakovL Sep 14 '16 at 10:08
  • 4
    Why would you expect to get 1 October after parsing a date for 31 September? – RobG Sep 14 '16 at 10:16

2 Answers2

1

Javascript Date object does that automatically.

Date Object

var str = "2016-09-31";
var d = new Date(str);
console.log(d.toDateString())

Moment

Logic:

  • Create date for 1st of any given month.
  • Fetch date from string and subtract 1 from it.
  • Add date value to moment variable using .add(date, 'day')

var str = "2016-09-31";
var arr = str.split(/(?:-|\/)/);
var d = moment(arr[0] + "-" + arr[1]+"-1").add(+arr[2]-1, "day").format("DD-MM-YYYY");
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.js"></script>
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • When parsing ISO 8601 format dates using the built–in Date constructor, it will be treated as UTC. Using *toLocaleString* for output will infer that it's been treated as local and for those west of Greenwich, will likely show a date [*for the previous day*](http://stackoverflow.com/questions/7556591/javascript-date-object-always-one-day-off/31732581#31732581). For me, your code shows `Invalid Date`. – RobG Sep 14 '16 at 10:12
  • @RobG not sure about `ISO` format issue. Will look into it. Thanks. – Rajesh Sep 14 '16 at 10:18
  • See [*ECMA-262 §20.3.3.2*](http://ecma-international.org/ecma-262/7.0/index.html#sec-date.parse) *Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN*. The result of setting the time value to NaN is an Invalid Date. – RobG Sep 14 '16 at 10:27
  • @RobG I have added a way to achieve using moment. Not sure if its the best option though. Also thanks for reference like. – Rajesh Sep 14 '16 at 10:41
1

According to ECMA-262, when parsing an ISO 8601 format date string, if any part is out of bounds the result must be an invalid Date. It seems to me that moment.js is being consistent with the standard.

If you want to create dates from invalid parts, you should do it manually.

/* Parse a date in ISO 8601 format as local
** Allow invalid parts
** @param {string} s - string to parse
** @returns {Date}
*/
function parseInvalidDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0], --b[1], b[2]);
}

console.log(parseInvalidDate('2016-09-31').toString())
RobG
  • 142,382
  • 31
  • 172
  • 209