Day360 in vb.net - vb.net

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

Related

VB.net work out number of days between two dates [duplicate]

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.

Excel VBA Comparing between a given date and (given date - 2 months)

I am writing a code to ensure that the data date of a system is not later than 2 business month-end date. For instance, if the job run date for the system is 23/12/2015, the valid data date is 30/10/2015 and 30/11/2015. The dates involved are only business days.
I have this code below:
If DateDiff("m", dataDate, jobRunDate) > 2 Then
MsgBox "Error in dataDate"
End If
However, I do not know how to find:
The last day of the month
Compute 2 business month back
Any help will be greatly appreciated. Thanks!
To find the last day of the month, you can find the first day of the next month and subtract a day:
Dim last As Date
Dim current As Date
current = Now
last = DateSerial(Year(current), Month(current), 1) - 1
Debug.Print last
To get the last business day of a month, just subtract days until it falls on a weekday:
Do While Weekday(last, vbMonday) > 5
last = last - 1
Loop
Debug.Print last
Combining the 2 ideas and extracting it as a function gets you this:
Private Sub Example()
Debug.Print LastBizDayOfMonth(Year(Now), Month(Now) - 1)
Debug.Print LastBizDayOfMonth(Year(Now), Month(Now) - 2)
End Sub
Private Function LastBizDayOfMonth(inYear As Integer, inMonth As Integer) As Date
LastBizDayOfMonth = DateSerial(inYear, inMonth + 1, 1) - 1
Do While Weekday(LastBizDayOfMonth, vbMonday) > 5
LastBizDayOfMonth = LastBizDayOfMonth - 1
Loop
End Function
Here is how to get the last day of a month:
Sub LastDayOfMonth()
Dim d As Date
mnth = 12
yr = 2015
d = DateSerial(yr, mnth + 1, 0)
MsgBox d
End Sub
You must then subtract two months from that date. If the result falls on a Saturday or Sunday, you must decide if you want to go forward to the next Monday or backward to the previous Friday.

Week number input returns crazy full week output

I would like some feedback on what's wrong with these codes. I'm trying to output a full week based on a week number. For instance if I input "2014/45" I would like to output all dates spanning from November 2nd to November 8th. Now I need to figure out the first date in that week (hence November 2nd) before grabbing the rest of the days and this is where everything gets messed up for me. This is what I've come up with:
' getyear = 2014, getweek = 45
Dim DateOfFirstWeekDay As DateTime = GetDateOfFirstDayOfWeek(getyear, getweek)
Dim FirstDateInSequence As DateTime = CDate(DateAdd("d", _
CInt(Abs(Integer.Parse(Weekday(DateOfFirstWeekDay, WeekStartsWith))) * -1) + 1, _
DateOfFirstWeekDay)).ToShortDateString()
Protected Friend Shared Function GetDateOfFirstDayOfWeek(ByVal getyear As Nullable(Of Integer), _
ByVal getweek As Nullable(Of Integer)) As DateTime
Dim firstWeekDay As DateTime = GetFirstDayOfWeek(newYearDay)
If getweek = 1 Then
getweek -= 1
End If
Return DateAdd(DateInterval.WeekOfYear, CInt(getweek), firstWeekDay)
End Function
Protected Friend Shared Function GetFirstDayOfWeek(ByVal dt As DateTime) As DateTime
If dt.DayOfWeek = DayOfWeek.Sunday Then
Return dt.AddDays(-6)
Else
Return dt.AddDays(1 - CInt(dt.DayOfWeek))
End If
End Function
As my question implies November 2nd is not the result I get. Instead FirstDateInSequence returns December 22, 2013 when I input 2014/45. It's pretty safe to assume something fails me here. I just can't get my head around it. I'd like your point of view to this. Where should I focus my attention in the code above?
I'm having a hard time quickly following your code logic. So here's mine.
You could start by finding the first day of the first week of that year
Dim d As New DateTime(year, 1, 1)
d = d.AddDays(-d.DayOfWeek)
And then add the number of days (week_number -1) * 7
d = d.AddDays((week_number - 1) * 7)
I do a -1 since I assume that week_number will be equal to 1 to get the first week. Since d is already equal to the first week, we start counting at 0.
To get the last day, just add 6 (or 7) days to the result

VBA Set a specific date to be the first week of the year

I want to set a specific date (October 06 , 2014) to be the 1st Week of the year. So when I use the =weeknum() formulaR1C1 it will return the week number.
I'm currently working on a worksheet that gets updated daily so the week number will be updated every week only. In column ("D") indicates the week number. and column ("B") indicates the daily date.
If i use the =weeknum() formula on it returns the value of 41, but it needs to be week number 1.
How about creating your personalized function?
It just consists of counting how many days there are between the date you insert (myDate) and the date which is considered to be the first day of the year (first_day), dividing this number by 7, taking its integer and adding up 1. It will always give you the right one.
Public Function special_weeknum(ByVal myDate As Date) As Integer
Dim first_day As Date: first_day = #10/6/2014#
Dim myWeek As Integer: myWeek = Int((myDate - first_day) / 7) + 1
special_weeknum = myWeek
End Function
Please note that this approach would allow you also to pass the first day as a user input:
Public Function special_weeknum(ByVal myDate As Date, ByVal first_day As Date)
Dim myWeek As Integer: myWeek = Int((myDate - first_day) / 7) + 1
special_weeknum = myWeek
End Function
so that you will always be able to decide which is the day you must consider as first day of the year.

VB.NET Make a Date out of just Day

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.