简体   繁体   English

如何计算excel中一年中的某一天的日期?

[英]How to calculate what date a particular day of the year is in excel?

I've found plenty of functions to determine what day of the year a particular date is : 我发现了很多功能可以确定特定日期是一年中的哪一天

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

But I haven't found any functions to determine the date, based on the day of a particular year. 但是我还没有找到任何功能可以根据特定年份的日期来确定日期。

The function signature would look like this: 函数签名如下所示:

Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date

Maybe something like this, 也许像这样

Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
    getDateBasedOnYearAndDayOfYear = dateserial(year, 1, 0) + dayofyear
end function

Just create a new date with January first of the passed year, then add the number of days. 只需在过去的一年的第一个月创建一个新日期,然后添加天数。 This is really easy in VBA, because Dates are just doubles with the integer portion representing the number of days since 12/31/1899. 在VBA中,这真的很容易,因为Date只是双精度的整数部分,代表自1899年12月31日以来的天数。

Start with this: 从此开始:

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

I'd probably add bounds checking and so forth, ie the -634th day of the year doesn't make much sense. 我可能会添加边界检查等,即一年的-634天没有多大意义。

Edit: 编辑:

Just tested against DateSerial - you don't even need to do the math: 刚刚针对DateSerial进行了测试-您甚至不需要做数学:

Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date

    getDateBasedOnYearAndDayOfYear = DateSerial(year, 1, dayOfYear)

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM