javascriptnode.jsdateleap-year

Convert milliseconds to years accurately, with decimal, in Javascript?


I'm trying to build an application similar to this. What it does is gives you the time since a specific date in years, with about 10-15 decimal places. I already took a look at this post, but every answer either didn't account for leap years, or didn't have the decimal precision this application requires. I'm not very good with dates in Javascript, could somebody help me out with this?


Solution

  • You can use Day.js.

    The example below should be used if you installed the library locally, with npm i dayjs or yarn add dayjs

    import dayjs from 'dayjs';
    import duration from 'dayjs/plugin/duration';
    
    dayjs.extend(duration);
    
    const getDuration = (start: Date | dayjs.Dayjs) => {
      // Gets the difference between now and some other date in ms
      const diff = dayjs().diff(start);
      // Converts the duration in ms to years
      return dayjs.duration(diff).asYears();
    };
    
    const dt = new Date('1990-10-09 09:30:15');
    const dj = dayjs('2000-01-01').startOf('day');
    
    console.log(getDuration(dt));
    console.log(getDuration(dj));
    

    You can also load it directly from the cdn like the snippet below.

    dayjs.extend(window.dayjs_plugin_duration)
    
    const getDuration = (start) => {
      const diff = dayjs().diff(start);
      return dayjs.duration(diff).asYears();
    };
    
    const dt = new Date('1990-10-09 09:30:15');
    const oneYearAgo = dayjs().subtract(1, 'year');
    const oneYearAndOneDayAgo = oneYearAgo.subtract(1, 'day');
    
    console.log(getDuration(dt));
    console.log(getDuration(oneYearAgo));
    console.log(getDuration(oneYearAndOneDayAgo));
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/duration.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>