Converting Google spreadsheet date into a JS Date object?

前端 未结 7 969
半阙折子戏
半阙折子戏 2020-12-01 12:49

I\'ve been going round in circles on this one... I\'ve got a spreadsheet which holds two dates, and I need to find the number of elapsed years between the two (ie. someone\'

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 13:31

    After some more experimenting, it turned out that it just works, which was a bit of a surprise. new Date(cell) seems to internally convert the serial number into a string which is sufficient to create the date object. Full answer:

    function datedif(first, second, format) {
      var e1  = new Date(first);
      var e2  = new Date(second);
      var age = e2.getFullYear() - e1.getFullYear();
      if(
          (e2.getMonth() <  e1.getMonth()) || 
         ((e2.getMonth() == e1.getMonth()) && (e2.getDate() < e1.getDate())))
        age--;
      return age;
    }
    

提交回复
热议问题