icambron / twix.js

:hourglass::left_right_arrow: A date range plugin for moment.js
https://isaaccambron.com/twix.js/
MIT License
379 stars 54 forks source link

humanizeLength() strict mode #32

Closed MarcBanc closed 10 years ago

MarcBanc commented 10 years ago
moment("5/25/1982 8:00").twix("5/25/1982 09:29").humanizeLength() 

returns "one hour", needed as "one hour, 29 minutes"

moment("5/25/1982 8:00").twix("5/25/1982 09:31").humanizeLength()

returns "two hours", needed as "one hour, 31 minutes"

its based on on 30min

but with:

moment("5/25/1982 8:00").twix("5/25/1982 08:11").humanizeLength()

it gives "11 minutes" and its OK

moment("5/25/1982 8:00").twix("5/25/1982 08:44").humanizeLength()

it gives "44 minutes" and its OK

but with

moment("5/25/1982 8:00").twix("5/25/1982 08:45").humanizeLength()

its gives "one hour" needed as "45 minutes"

its based on 15min

it is possible?

icambron commented 10 years ago

humanizeDuration() lets Moment's from() method do the heavy-lifting (see http://momentjs.com/docs/#/displaying/from/). There have been a few requests to allow Moment's humanization functions to be customizable (see, e.g. https://github.com/moment/moment/issues/892). If that's ever implemented, I will certainly add support for it to humanizeDuration(). But in the meantime, I'm not keen on having special logic for it in Twix itself.

Fortunately, it's easy to build a custom function to do what you want. Just add this to your code to augment Twix:

Twix.prototype.humanizeFifteens = function(){
  var output = "",
      duration = this.asDuration(),
      hours = duration.get('h'),
      //maybe want to do some rounding here, e.g (min % 15) * 15
      mins = duration.get('m');

  if (hours > 0){
    output += hours + " hours";
  }
  if (mins > 0 && hours > 0) {
    output += " ";
  }
  if (mins > 0) {
    output += mins + " minutes";
  }
  return output;
}

Which allows you to do:

moment("5/25/1982 8:00").twix("5/25/1982 08:45").humanizeFifteens(); //=> "45 minutes"
moment("5/25/1982 8:00").twix("5/25/1982 09:45").humanizeFifteens(); //=> "1 hours 45 minutes"

Modify according to your needs.

MarcBanc commented 10 years ago

Thanks a lot!