## Friday, 22 March 2013

### Duration Calculator for Dates in VB.NET

Hello Guys,
I was working on a project of a hotel management system. I had to calculate the day between two given dates by DateTimePicker in vb.NET.
I named the DateTimePicker as "DTPcheckin" for the day when customer checks into the hotel and
"DTPcheckout" for the date of checkout.
To calculate the date and to facilitate myself for the later calculation and SQL comparisons I converted the date to the NUMBER OF DAYS FROM THE BEGINNING OF THE CALENDER .
LIKE "20 MARCH 2013" == 735328. that is 735328 days passed from date 01/01/0001.
U can use this anywhere you want. here is the code------

Dim checkin_day As Integer
Dim checkout_day As Integer
Dim checkin_month As Integer
Dim checkout_month As Integer
Dim checkin_y As Integer
Dim checkout_y As Integer
Dim staying As Integer
Dim mdcin As Integer
Dim mdcout As Integer
Dim daycin As Integer
Dim daycout As Integer

Private Sub calday()
checkin_day = CInt(DTPcheckin.Value.Day)
checkout_day = CInt(DTPcheckout.Value.Day)
checkin_month = CInt(DTPcheckin.Value.Month)
checkout_month = CInt(DTPcheckout.Value.Month)
checkin_y = CInt(DTPcheckin.Value.Year)
checkout_y = CInt(DTPcheckout.Value.Year)

mdcin = mdcount(checkin_month)
mdcout = mdcount(checkout_month)
daycin = checkin_y * 365 + mdcin + checkin_day
Dim temp2 As Integer = checkin_y - 1
temp2 = temp2 / 4
daycin = daycin + temp2

If (checkin_y Mod 400 = 0 Or (checkin_y Mod 100 <> 0 And checkin_y Mod 4 = 0)) And checkin_month > 2 Then
daycin = daycin + 1
End If

daycout = checkout_y * 365 + mdcout + checkout_day
Dim temp As Integer = checkout_y - 1
temp = temp / 4
daycout = daycout + temp
If (checkout_y Mod 400 = 0 Or (checkout_y Mod 100 <> 0 And checkout_y Mod 4 = 0)) And checkout_month > 2 Then
daycout = daycout + 1
End If
//duration is calculate by subtracting the daycin from daycout
duration = daycout - daycin
End Sub

//the mdcount function is
//this  mdcount function calculate the number of days from 1st jan to the given month
Public Function mdcount(ByVal n As Integer) As Integer
Dim md As Integer

If n = 1 Then
md = 0
ElseIf n = 2 Then
md = 31
ElseIf n = 3 Then
md = 59
ElseIf n = 4 Then
md = 90
ElseIf n = 5 Then
md = 120
ElseIf n = 6 Then
md = 151
ElseIf n = 7 Then
md = 181
ElseIf n = 8 Then
md = 212
ElseIf n = 9 Then
md = 243
ElseIf n = 10 Then
md = 273
ElseIf n = 11 Then
md = 304
ElseIf n = 12 Then
md = 334
End If
Return md
End Function

#### 2 comments:

1. 2. 