如何计算 excel 中某一天的日期?
How to calculate what date a particular day of the year is in excel?
我找到了很多函数来确定特定日期是一年中的哪一天:
Function Yearday(dat As Date) As Integer
'Purpose: does the same as day for month
'Use to access an array where the index corresponds to days
Yearday = DateDiff("d", CDate("1/1/" & Year(dat)), dat) + 1
End Function
但是我还没有找到任何函数来根据特定年份的某一天来确定日期。
函数签名如下所示:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
只需用过去一年的一月一日创建一个新日期,然后加上天数。这在 VBA 中非常容易,因为日期只是双倍的整数部分,表示自 12/31/1899 以来的天数。
从这里开始:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date
Dim result As Date
result = DateSerial(year, 1, 1)
getDateBasedOnYearAndDayOfYear = result + dayOfYear - 1
End Function
我可能会添加边界检查等等,即一年中的第 -634 天没有多大意义。
编辑:
刚刚针对 DateSerial 进行了测试 - 您甚至不需要计算:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date
getDateBasedOnYearAndDayOfYear = DateSerial(year, 1, dayOfYear)
End Function
也许是这样的,
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
getDateBasedOnYearAndDayOfYear = dateserial(year, 1, 0) + dayofyear
end function
我找到了很多函数来确定特定日期是一年中的哪一天:
Function Yearday(dat As Date) As Integer
'Purpose: does the same as day for month
'Use to access an array where the index corresponds to days
Yearday = DateDiff("d", CDate("1/1/" & Year(dat)), dat) + 1
End Function
但是我还没有找到任何函数来根据特定年份的某一天来确定日期。
函数签名如下所示:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
只需用过去一年的一月一日创建一个新日期,然后加上天数。这在 VBA 中非常容易,因为日期只是双倍的整数部分,表示自 12/31/1899 以来的天数。
从这里开始:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date
Dim result As Date
result = DateSerial(year, 1, 1)
getDateBasedOnYearAndDayOfYear = result + dayOfYear - 1
End Function
我可能会添加边界检查等等,即一年中的第 -634 天没有多大意义。
编辑:
刚刚针对 DateSerial 进行了测试 - 您甚至不需要计算:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date
getDateBasedOnYearAndDayOfYear = DateSerial(year, 1, dayOfYear)
End Function
也许是这样的,
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
getDateBasedOnYearAndDayOfYear = dateserial(year, 1, 0) + dayofyear
end function