gr2m / moment-parseformat

A moment.js plugin to extract the format of a date/time string
http://gr2m.github.io/moment-parseformat
Apache License 2.0
45 stars 30 forks source link

Return failure when encountering unknown format #9

Closed theazureshadow closed 9 years ago

theazureshadow commented 10 years ago

If I use moment.parseFormat('yesterday'), I get a format of 'yesterday'. I'd rather be able to tell that parseFormat didn't recognize the format, for example by returning undefined.

gr2m commented 10 years ago

Yeah I see your point. I agree there should be a way to determine if no date/time format has been found at all, returning undefined won't do it though. I'd rather add a way to check the input with methods like hasDate / hasTime / hasDateTime whether respective formats could be found.

Can you describe your use case here?

onecreative commented 10 years ago

I agree that undefined is not the best choice of words, but the concept is good. Perhaps, an object with two parts could be returned:

  1. The resulting value, which in this case is yesterday.
  2. A status code/comment.

Then we could use the status code as a way of telling our own script what to do next.

gr2m commented 10 years ago

returning an object with two parts adds too much complexity. What speaks against this:

moment.parseFormat.hasDate('yesterday') // false
onecreative commented 10 years ago

I like that better

theazureshadow commented 9 years ago

My use case is to validate that a date entered by the user contains enough pieces to accurately identify a day (e.g. has day and month with implied year, or has day, month, and year), and isn't just a random string they entered, like "I want 20 October apples".

A boolean might not give enough information for some validations like this. Another option would be to provide a second parse method that which shows what parts of the input were calculated as a date:

moment.parseFormat.parseToArray("yesterday")
// returns [], since nothing could be converted to a format string

moment.parseFormat.parseToArray("8th January 1986")
// returns [
  {pos:0, len:3, fmt: "Do"},
  {pos:4, len:7, fmt: "'MMMM"},
  {pos:12, len:4, fmt: "YYYY"}
]

A simpler option that would address my use case, (but not be quite as useful) would be to return a mask of the unconsumed input:

moment.parseFormat.parseToMask("8th January 1986")
// returns                     "                "
moment.parseFormat.parseToMask("This is the 8th of May")
// returns                     "This is the     of    "
gr2m commented 9 years ago

@theazureshadow would you like to try build the parseToArray method? We could either incorporate it into core, or if it becomes too big, make it an external file that'd you'd only load if you need the method?

gr2m commented 9 years ago

closing in favor of #9

LarryBattle commented 8 years ago

@gr2m meant #26