andrewplummer / Sugar

A Javascript library for working with native objects.
https://sugarjs.com/
MIT License
4.53k stars 306 forks source link

Getting access to date specificity #589

Open praxiq opened 7 years ago

praxiq commented 7 years ago

Sometimes it's useful to think of an incompletely-specified date as a range. "March 4" refers to a whole day: from March 4 at 12:00:00 AM to March 5 at 12:00:00 AM. "March 4th 2:00 pm" refers to a whole minute: from March 4th at 2:00:00 PM to March 4th at 2:01:00 PM."

To put it another way, there's a big difference between telling someone, "Do this on March 4th" and "Do this on March 4th at 12:00:00 AM", but Sugar returns the same Date object with full specificity either way.

For example, in a calendar app, if a user says to create an event on "March 4th" without specifying a time, they probably don't mean at midnight. Perhaps they want to create a full-day event, or to use a default time - but if I parse the date with Sugar, I can't know what specificity they entered!

I've been looking for a date parsing library that lets me know the specificity at which a date was provided. I see that Sugar's internal getExtendedDate does calculate that specificity, but doesn't seem to expose it in the API at all. I would love to see an API call that exposed the specificity - or better yet, the whole "set" object, so that I could know exactly which parts of the date were provided and which were implied by context.

andrewplummer commented 7 years ago

It actually does now! Have a look at the docs for the params option. If you pass an object here, it will be populated with various parsed attributes, one of which is "specificity" that is an index:

0 = millisecond
1 = second
2 = minute
3 = hour
4 = day
5 = week
6 = month
7 = year

In future versions I am planning on improving the docs here and exposing these numbers as constants to improve readability.

praxiq commented 7 years ago

Aha! I skimmed the source and saw that there was no place where the set returned by getExtendedDate was exposed. It didn't occur to me to check for mutating the arguments! Thanks for this.

andrewplummer commented 7 years ago

I'll leave this open as a reminder to improve the docs for this one. Thanks!