Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get First And Last Day Of Year

In VBA I know you can use this syntax to subtract a year from a date

Dim testdate As String, DateTest As String
testdate= "03/21/2017"
DateTest = Month(testdate) & "/" & Day(testdate) & "/" & Year(testdate) - 1

But how could you find the first and last date of a given year? For example, let's use the same date

testdate = "03/21/2017"

and get the following values

firstdate = "01/01/2017"
lastdate = "12/31/2017"
like image 918
IcyPopTarts Avatar asked Dec 13 '22 23:12

IcyPopTarts


2 Answers

You can use DateSerial:

Sub Test()

    Dim dt As Date, firstDay As Date, lastDay As Date

    dt = Date
    firstDay = DateSerial(Year(dt), 1, 1)
    lastDay = DateSerial(Year(dt), 12, 31)

    Debug.Print firstDay
    Debug.Print lastDay

End Sub
like image 196
Fadi Avatar answered Jan 04 '23 17:01

Fadi


If it is always the beginning and the end of the year that interest you, you can just use the 1st of January and the 31st of december. To mimic your syntax :

Dim testdate As String, DateTest As String
testdate= "03/21/2017"
FirstDayOfYear = "1/1/" & Year(testdate)
LastDayOfYear = "12/31/" & Year(testdate) 
like image 41
WNG Avatar answered Jan 04 '23 19:01

WNG