This question already has answers here:
How to find the number of days between two dates / DateTimePickers
(3 answers)
Closed 6 years ago.
I am trying to work out the number of days between two dates and whether it is a full month or not.
I currently have this code:
Dim fromdate As Date
Dim todate As Date
Dim timespan
Dim num_days As String
Dim month As DateTime
fromdate = Date.Parse("01/01/2017")
todate = Date.Parse("31/01/2017")
TimeSpan = todate - fromdate
num_days = TimeSpan.Days
MsgBox(num_days)
And then I try to work out if it is a full month:
month = todate
If (month.Month = "02" And num_days = "28") Or num_days = "29" Or num_days = "30" Or num_days = "31" Or num_days = "0" Then
'do code here
Else
'do code here
End If
But this is proving to not work in February because it only sees the num_days as 27
Is there a way I can get the correct number of days between the two dates including the dates themselves being full days?
And how can I check if it is a full, correct month or not
UPDATE
The purpose of this is for a billing system so files are read into a database with from and to dates then it needs to work out the pricing from those dates.
So a product has a specific price, but first of all we need to work out whether to bill for part of a month or a full month (basically part of the product price or the full price)
So these 'Full Month' date range examples will bill the full price
Full Month:
01/01/2017 - 31/01/2017
25/01/2017 - 25/01/2017
18/01/2017 - 18/02/2017
10/01/2017 - 10/01/2018
Whereas, this date range for 'Part Month' will only bill for the number of days between the from and to date (+1 day)
Part Month
15/01/2017 - 31/01/2017
This would get what you specified:
Dim IsOneFullMonth = (d1.Day = 1 And d2 = d1.AddMonths(1).AddDays(-1))
Dim IsOnMonthLater = (d2 = d1.AddMonths(1))
The two states are not really the same thing in my understanding.
The second check is one month and one day.
(The first would match 'Jan 01 - Jan 31', the second one 'Jan 01 - Feb 01'.)
Also consider that neither check would match 'end of months' like 2016-02-29 - 2016-03-31 - you have to really define what you want to achieve in those cases.
Related
I've got the following formula
number_of_years = DateDiff("yyyy", Date_days_back, Current_Date)
where
Date_days_back = 17/10/2020
Current_Date = 02/08/2021
for some reason this returns "1" when there aren't 365 days apart between these two dates, is something wrong with my formula or is DateDiff calculating this wrong? I would like to get "0" returned as there aren't enough amount of days between these two dates for a year to have passed between the two dates.
Comment: As Scott Stated, if I'm looking from December 31st 2020 and 1st of January 2021, then this function will count this as a year has passed. is there another function that calculates if a years has passed in between two dates where it doesn't do what DateDiff does and instead counts if 365 have passed in between the two dates?
Try to use YearFrac(). By setting the third argument to 1, the function uses the actual number of days in years (taking into account leap years) in its calculations:
Int(WorksheetFunction.YearFrac("2020-12-31", "2021-12-31", 1))
Comparison:
Sub Example()
start_date = CDate("2020-12-31")
end_date = CDate("2021-01-01")
Debug.Print Int(WorksheetFunction.YearFrac(start_date, end_date, 1))
' prints 0
Debug.Print DateDiff("yyyy", start_date, end_date)
' prints 1
End Sub
This seems to work
function yeardiff(d1 as date, d2 as date) as integer
yeardiff = datediff("yyyy", d1, dateadd("yyyy", -1, dateadd("d", 1, d2)))
end function
Tests
print yeardiff("2020-12-31", "2021-12-30")
0
print yeardiff("2020-12-31", "2021-12-31")
1
Of course it will also give,
print yeardiff("2020-12-31", "2020-12-30")
-1
And if something different is desired then a conditional would be needed.
Macro does not appear to be taking days into account when calculating a person's age.
Sub alcohol_test()
Dim strBirthday As Date
strBirthday = CDate(InputBox("Input date of birth to be verified: ", "Date of Birth"))
If DateDiff("yyyy", strBirthday, Date) < 21 Then MsgBox ("Customer underage, sale of alcohol illegal.") _
Else MsgBox ("Age Confirmed: Alcohol may be sold")
End Sub
It is even worse:
When comparing December 31th to January 1st of the immediately succeeding year,
DateDiff for Year ("yyyy") returns 1, even though only a single day has elapsed, says Microsoft.
So you better compare two dates, e. g. if the birthday was before the day 21 years ago.
Dim datBirthday as Date
datBirthday = CDate(InputBox("Input date of birth to be verified: ", "Date of Birth"))
If datBirthday < DateSerial(Year(Date) - 21, Month(Date), Day(Date)) Then
I changed the variable name, as a beginning with "str" is a little misleading when you use date values.
Suppose the flow of time is subdivided into periods:
Period 1 beginning August and ending January
Period 2 beginning February and ending July
Note, that each period is 6 month.
Question
Now suppose two dates A and B are given.
Could you provide an expression (closed formula), which computes the
number of periods where A is within the first and B is within the last
period?
'Closed formula' :: The creation of a procedure isn't an option her.
Let's have a detailed look
Let...
A be the 2nd of March 2015
B be the 15th of January 2018
Thus...
A is part of period 2 beginning February 2015.
B is part of period 1 beginning August 2017.
Therefore...
the difference in periods between A and B is 6.
Since
Period 2 beginning February 2015
Period 1 beginning August 2015
Period 2 beginning February 2016
Period 1 beginning August 2016
Period 2 beginning February 2017
Period 1 beginning August 2017
Try looking into the VBA function DateDiff https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/datediff-function
As formula (assuming your date in A2 and B2):
=(YEAR(EDATE(A2;-1))*2+INT((MONTH(EDATE(A2;-1))-1)/6)) - (YEAR(EDATE(B2;-1))*2+INT((MONTH(EDATE(B2;-1))-1)/6))
As VBA function:
Function datePeriods(ByVal d1 As Date, ByVal d2 As Date) As Long
d1 = DateAdd("m", -1, d1)
d2 = DateAdd("m", -1, d2)
Dim p1 As Long, p2 As Long
p1 = Year(d1) * 2 + ((Month(d1) - 1) \ 6)
p2 = Year(d2) * 2 + ((Month(d2) - 1) \ 6)
datePeriods = p2 - p1
End Function
The basic idea is to "move" the periods to the first and second half of a year, then calculate a numeric value for the year (year * 2) and the "half year" (integer division by 6) and subtract these two values.
Code to test your function. Insert a module in the VBA editor and enter the following code in it:
Option Explicit
Public Function CountPeriods(startDate As Date, endDate As Date) As Long
Dim diffMonths As Long
Dim diffPeriods As Long
diffMonths = DateDiff("m", startDate, endDate)
diffPeriods = diffMonths \ 6
CountPeriods = diffPeriods
End Function
Now enter your start and end dates and refer to the code above like this in cell B1 (or any cell):
I want to use the Days360 function in VB.Net. I need to know the difference in days between two dates assuming 360 days in a year (not 365 days the DateDiff function uses).
For example DateDiff(DateInterval.Day,"16/10/2015", "04/02/2016") = 111 days, but Days360 should return 109 days.
Days360 function in Excel calculates the days between two dates using a fictional calendar that has 30 days in each month. This method is used for some financial purposes.
You can write a function to do the same calculation.
[Edit]
Excel supports two versions of the calculation: one common in the US (this is the default) and the other common in Europe (see the documentation of the DAYS360 function for details).
The code I originally posted implemented the European version. I have updated it to support both versions. Thanks to Nikhil Vartak for pointing this out.
Function Days360(startDate As DateTime, endDate As DateTime, euMethod As Boolean) As Integer
Dim months As Integer = (endDate.Year - startDate.Year) * 12 + endDate.Month - startDate.Month
If euMethod Then
'Use European method (start or end dates after the 30th of the month are changed to 30th)
Return months * 30 + Math.Min(30, endDate.Day) - Math.Min(30, startDate.Day)
Else 'Use US method
'If the start date is the last day of the month, change it to the 30th
Dim startDay As Integer = startDate.Day
startDay = If(startDate.Day >= DateTime.DaysInMonth(startDate.Year, startDate.Month), 30, startDate.Day)
'If end date is last of the month, change it to the 30th
Dim endDay As Integer = endDate.Day
endDay = If(endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month), 30, endDate.Day)
'If end date is last of the month and start date is before 30th, change end date to 1st of the next month
If endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month) And startDay < 30 Then
endDay = 1
months += 1
End If
Return months * 30 + endDay - startday
End If
End Function
My user will typically enter some trip info including a day and month but typically they just enter the day. For example they would enter "TRIP1500/31" where the 31 is implied that its in JULY. The trip date can be at most 7 days in the past or 7 days in the future. So now what Im trying to do is guess what month that day is meant to be. So far I have:
Dim diff As Integer = CInt(tripDay) - Date.Now.Day
Select Case diff
Case 0
'same day so its probably current month
End Select
What I'm having trouble with is the other cases where the current day and the trip day overlap month-to-month. If the current day and trip day are in current month then the most difference they can be is +/-7 days but what about the other cases? Any help appreciated.
Function GetTripDate(day As Integer) As Date
Dim today As Date = Date.Today
For i As Integer = -7 To 7
Dim dt As Date = today.AddDays(i)
If dt.Day = day Then Return dt
Next
Throw New ArgumentOutOfRangeException("Invalid trip day.")
End Function
This gives you the date(incl. month) of the nearest date with the given day:
Dim maxDiffDays = 7
Dim tripDay = 31
Dim today = Date.Today
Dim tripDate = New Date(today.Year, today.Month, tripDay)
Dim tripDates = {tripDate.AddMonths(-1), tripDate, tripDate.AddMonths(1)}
Array.Sort(Of Date)(tripDates, Function(d1, d2) ((today - d1).Duration).CompareTo((today - d2).Duration))
Dim nearestDate = tripDates.First()
If ((today - nearestDate).Days <= maxDiffDays) Then
Console.WriteLine("Nearest month for trip date is: " & nearestDate.Month)
End If
It creates a Date from a given day, then it creates the two surrounding dates one month after and previous this date. This array will be sorted from the positive timespan from today(TimeSpan.Duration). So the firs't date in the array is the nearest date with the correct month.