有可能计算两个日期之间的距离在几个月还是几年? [英] Is it possible to count the distance between two dates in months or years?

查看:178
本文介绍了有可能计算两个日期之间的距离在几个月还是几年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

difftime()函数可以方便地计算两个日期之间的差异,但不能计算月份或年份的差异。有什么理由吗?你会知道执行这个任务的任何功能吗?

The difftime() function makes it easy to compute the difference between two dates in days or in weeks but there is no option to compute the difference in months or in years. Is there any reason for that ? Would you know any function which would perform this task ?

推荐答案

从评论中:几个月和几年不是精确的时间单位,也就是他们长度有所不同(月份可以有28,29,30,31天,年份可以有365或366)。如果要修复这些单位之一的值(例如,月份= 30天,年= 365天),您可以将天数中的 difftime 固定值以获得所需单位的差异。或者如果您只想要两个日期之间的完整月份数量,您可以执行此操作

From the comments: Months and years aren't precise time units, that is, their lengths vary (months can have 28, 29, 30, 31 days. Years can have 365 or 366). If you want to fix a value for one of these units (e.g., month = 30 days, year = 365 days), you can just divide your difftimes in days by the fixed value to get the difference in the units you want. Or if you just want something like the number of complete months between two dates, you could do this

date1 = as.Date('2012-1-2')
date2 = as.Date('2012-7-5')
length(seq(from=date1, to=date2, by='month')) - 1
# [1] 6

或几周:

length(seq(from=date1, to=date2, by='week')) - 1
# [1] 26

这篇关于有可能计算两个日期之间的距离在几个月还是几年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆