Search code examples
javascriptdatedate-fns

Javascript date-fns more specific distanceInWords


I'm using distanceInWord to know how many time there is between 2 dates. But it's not exactly what I want because I need to be more specific.

For example if I have this : 1 January 2019 15:00:00 and 1 January 2019 16:30:00

Actually it returns 1 hour with distanceInWordStrict() or about 1 hour with distanceInWord().

So I need to get 1h30 for this.

How can I do to be more specific ? 1h30, 2h15, 3h45, 2 days and 5 hours etc...


Solution

  • You can't do that with distanceInWord according to docs, as it created for wide ranges and short result strings (about 7 years instead of 7 years, 4 months, 7 weeks, 3 days and 5 seconds). You can only force units in distanceInWordStrict - passing {unit: 'm'} as a third parameter will output 90 minutes.

    But you can get the difference between dates with any units and according to result - format as you'd like to. Something like this:

    let result;
    
    const date1 = '1 January 2019 15:00:00';
    const date2 = '1 January 2019 16:30:00';
    
    const minutes = Math.abs(differenceInMinutes(date1, date2));
    
    if(minutes < 60) {
      result = distanceInWordsStrict(date1, date2, {unit: 'm'})
    }
    else {
      result = distanceInWordsStrict(date1, date2, {unit: 'h'});
      result = result.replace(/ hours?/, `h${minutes % 60}m`)
    }
    

    If you never go over hours, then this would be a simpler formatting approach:

    const hours = Math.abs(differenceInHours(date1, date2);
    result = `${hours}h${minutes % 60}m`;
    

    Also, you could simply get the difference in milliseconds, create a date object from it and format in any way you like.

    Note that if you'll have a difference more than a day it will be output with a number of hours. So the final solution mostly depends on your variety of possible ranges.