Create HTML on Specific Time - vb.net

If have the following Code:
Public Shared Function GetNextWeekDay() As Date
Dim value As Date = Date.Now
Do
value = value.AddDays(1)
Loop While (value.DayOfWeek = DayOfWeek.Saturday) Or (value.DayOfWeek = DayOfWeek.Sunday)
Return value
End Function
Public Shared Function DPLoadData() As String
Dim s As StringBuilder = New StringBuilder("<head><meta http-equiv=""content-type"" content=""text/html;charset=utf-8"" /><META HTTP-EQUIV=""REFRESH"" CONTENT=""900"">")
s.Append("<style type=""text/css"" media=""all""> body{font-family: Arial;}h4{font-size: 10pt;font-weight: bold;white-space: nowrap;margin-top: 0; margin-bottom: 10px;}")
s.Append("th{font-size: 9pt;font-weight: normal;text-align: center;white-space: nowrap;}td{font-size: 9pt;}.content td{border: solid 1px #dadada;}")
s.Append(".content th {border: solid 1px #dadada;background-image: url(""tbl_header_row_bg.gif""); background-repeat: repeat-x; white-space: nowrap;}</style></head>")
s.Append("<h3>" & "Daily Plan" & "</h3>")
Dim strCurrDay As String = ""
s.Append("<h5>" & strCurrDay & "</h5>")
Dim CurrDateFirstDay As Date = GetNextWeekDay()
strCurrDay = FormatDateTime(CurrDateFirstDay, DateFormat.LongDate)
s.Append("<h5>" & strCurrDay & "</h5>")
s.Append(LoadDataGroupByDate(CurrDateFirstDay))
Return s.ToString()
End Function
The function DPLoadData generates an HTML file with a table and fills it with bookings. Currently, the HTML file displays the bookings of tomorrow (e.g. if today is Monday, it displays the bookings for Tuesday and if today is Friday, it displays the bookings for Monday).
What i need is that the HMTL file gets generated at 5 p.m. For Example: If today is Monday, then the HTML file should be generated Monday at 5 p.m and should display the bookings for Tuesday until Tuesday 5 p.m and Tuesday at 5 p.m the file should be generated for wednesday and should display the bookings for wednesday until wednesday 5 p.m, and so on.
How can i do that? Please help.
My Solution:
Public Shared Function GetNextWeekDay() As Date
Dim value As Date = Date.Now
Dim intHour As Integer
Dim intMinute As Integer
Dim intSecond As Integer
intHour = 17
intMinute = 0
intSecond = 0
Dim newdatetime As DateTime = New Date(value.Year, value.Month, value.Day, intHour, intMinute, intSecond)
If DateTime.Now < newdatetime Then
If value.DayOfWeek = DayOfWeek.Saturday Then
value = value.AddDays(2)
Return value
End If
If value.DayOfWeek = DayOfWeek.Sunday Then
value = value.AddDays(1)
Return value
End If
Return value
ElseIf DateTime.Now > newdatetime Then
Do
value = value.AddDays(1)
Loop While (value.DayOfWeek = DayOfWeek.Saturday) Or (value.DayOfWeek = DayOfWeek.Sunday)
Return value
End If
End Function

As I understand your question, you are basically looking for a way to execute a program at a given time? If so, have a look at cron or the Windows scheduler, depending on the OS you are running this on.
Update: So basically you just need to compare the current time and check whether it is before 5pm. Then you should have a function which return the data from 5pm current day until 5pm tomorrow.
You might want to have a look at this VB tutorial for DateTime. Basically you need to compare the current time with a date time consisting of the current date at 5pm.
Update: Just extend your if condition to also check that today is not Saturday or Sunday. Here's a little code snippet I just whipped up. I am not really familiar with VB, so this might not be 100% correct, but I think you get the idea.
Public Function GetNextWeekDay() As Date
Dim value As Date = Date.Now
Dim intHour As Integer
Dim intMinute As Integer
Dim intSecond As Integer
intHour = 17
intMinute = 0
intSecond = 0
Dim newdatetime As DateTime = New Date(value.Year, value.Month, value.Day, intHour, intMinute, intSecond)
If value.DayOfWeek <> DayOfWeek.Saturday And value.DayOfWeek <> DayOfWeek.Sunday And DateTime.Now < newdatetime Then
Return value.Date
Else
Do
value = value.AddDays(1)
Loop While (value.DayOfWeek = DayOfWeek.Saturday) Or (value.DayOfWeek = DayOfWeek.Sunday)
Return value.Date
End If
End Function

Related

VB.Net find last day of month with date format

I am trying to find the last day of the month and compare it to today's date
I do NOT want the integer number I would like the result in this format "MM-dd-yyyy"
Date Picker will not work for this project
Here is the code I using but the process seems overly complicated concocting strings
Side note when today is after the 4th Tue I write True and the Last Day of the month to a DB
when today is after the last day of the month and the bool is now True I write the new last day of the new month and false to the DB
Function FourthTueOfMonth(dt As Date) As Date
Dim currDate = New Date(dt.Year, dt.Month, 1)
Dim nTuesday = 0
While nTuesday < 4
If currDate.DayOfWeek = DayOfWeek.Tuesday Then
nTuesday += 1
End If
currDate = currDate.AddDays(1)
End While
Return New Date(dt.Year, dt.Month, currDate.Day - 1)
End Function
Private Sub btnFindDate_Click(sender As Object, e As EventArgs) Handles btnFindDate.Click
Dim tORf As Boolean = False
Dim dateToday = Date.Today
Dim dateFourthTue = (FourthTueOfMonth(Date.Today))
tbFourthTue.Text = dateFourthTue.ToString("MMM-dd-yyyy")
tbThree.Text = dateFourthTue.ToString("yyyy-MM-dd")
tbEndOFMonth.Text = Date.DaysInMonth(Date.Now.Year, Date.Now.AddMonths(0).Month).ToString
Dim dToday As Date
dToday = Date.Parse("10-01-2021")
Dim dtY = dateToday.ToString("yyyy")
Dim dtM = dateToday.ToString("MM")
Dim eom As String = Date.DaysInMonth(Date.Now.Year, Date.Now.AddMonths(0).Month).ToString
Dim dtALL As String
dtALL = dtM & "-" & eom & "-" + dtY
Dim testD As Date
testD = Date.Parse(dtALL)
If tORf = False And dToday > dateFourthTue Then
MessageBox.Show("Today > Fourth Tue")
'tORf = True'Write True
'tbMessage.Text = tORf.ToString
End If
If tORf = True And dToday > testD Then
MessageBox.Show("Today > End Of Last Month")
'tORf = False write False
'tbMessage.Text = tORf.ToString
End If
End Sub
The solution provided by #Albert D. Kallal is great for Visual Basic since DateSerial is in the Visual Basic namespace in the DateAndTime class. Here is a solution that should work in both vb and C#.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dtToday As Date = Date.Today
Dim dtEndOfMonth = New Date(dtToday.Year, dtToday.Month + 1, 1).AddDays(-1)
Debug.Print(dtToday.ToString)
Debug.Print(dtEndOfMonth.ToString("MM-dd-yyyy"))
End Sub
A few things:
You want to use today - not "now()" as that includes a time portion. While a date type only has date, you should consider if you have datetime, and either way, no need to introduce and use a value that includes both date and time such as now does.
I reocmmend this code:
Dim dtToday As Date = Date.Today
Dim dtEndOfMonth As Date = DateSerial(dtToday.Year, dtToday.Month + 1, 0)
Debug.Print(dtToday)
Debug.Print(dtEndOfMonth)
Output:
Today happens to be the 1st, but any date would work. This includes end of year, and even leap years.
2021-10-01
2021-10-31
So, this is a long time old trick - goes back to old VB6, and even old VBA code from 20 years ago.
So, we use date serial to produce a date, but if you use 0 for the day, then you get the previous day, and thus gets you the last day of the current month.
So we toss in year, month + 1, and 0 for the date - that results in the last day of the current month.
I hate to admit I might have gave up the search too quick
found the answer here
Answer Here
Here is the code
Dim dateToday = Date.Now.AddMonths(0)
Dim dateEndOfMonth = New Date(dateToday.Year, dateToday.Month, DateTime.DaysInMonth(dateToday.Year, dateToday.Month))
tbMsg.Text = dateEndOfMonth.ToString("MM-dd-yyyy")
Code seems to be working ?
I have seen suggestions to use this format for comparing dates
TEST DATES use this format yyyyMMdd Please comment if you can add to the answer

Get same nth day of the month in x number of months

I am needing some help converting a function from access vba to vb.net.
The script generates a new date, based on the date entered, and the number of months to be added.
“If today is the second Tuesday in March, what will be the second Tuesday in 4 months?”
Public Function NdNwk(dType As String, _
dtSpan As Integer, sDate As Date) As Variant
' This Function RETURNS the DAY of WHICH WEEK
' (e.g. Second Tuesday of the Month).
' FUNCTIONS to be passed to Variables:
' gtDoW: Day of the WEEK of the START DATE.
' (1 for Sunday, 2 for Monday, etc.)
' gtWoM: WEEK of the MONTH of the START DATE.
' (1 for First, 2 for Second, etc.)
' gtDSTdt: Desired DATE
' (generated by the [DateAdd] Function).
' CALL EXAMPLE: If TODAY is Tuesday, March 10, 2020,
‘ (second Tuesday of March), then using
' NdNwk(m, 2, #5/21/2020#)
' Would generate the DATE 5/12/2020,
' As the SECOND TUESDAY of MAY.
Dim gtDSTdt As Date, gtWoM As Integer, gtDoW As Integer
Dim iLoop As Integer, iPick As Integer, dstDTdom As Date
gtDoW = Weekday(sDate)
gtWoM = (Int((Day(sDate) - 1) / 7) + 1)
gtDSTdt = DateAdd(dType, dtSpan, sDate)
For iLoop = 1 To Day(DateSerial(Year(gtDSTdt), _
Month(gtDSTdt) + 1, 0))
dstDTdom = DateSerial(Year(gtDSTdt), _
Month(gtDSTdt), iLoop)
If Weekday(dstDTdom, 1) = gtDoW Then
iPick = iPick + 1
If iPick = gtWoM Then
NdNwk = dstDTdom
Exit Function
End If
End If
Next
End Function
Any and all help is appreciated here.
I used several of the properties and methods of the .net DateTime structure. https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netcore-3.1
The arithmetic in the Function used the Mod operator which returns the remainder of the division. The integer division (the formard slash \) returns the integer portion of the division.
The only other thing that might be unfamiliar is the interpolated string, a string starting with $"". This allows you to directly embed variables in the string surround by { }.
Private Function NdNwk(InputDate As Date, MonthsAhead As Integer) As String
Dim newDate As Date
Dim DofWeek = InputDate.DayOfWeek
Dim Day = InputDate.Day
Dim OfInputMonth As Integer
If Day Mod 7 = 0 Then
OfInputMonth = Day \ 7
Else
OfInputMonth = (Day \ 7) + 1
End If
Dim TempDate = InputDate.AddMonths(MonthsAhead)
Dim NewMonth = TempDate.Month
Dim NewYear = TempDate.Year
Dim FirstWeek As Date
Dim NewDay As Integer
For d = 1 To 7
FirstWeek = New Date(TempDate.Year, TempDate.Month, d)
If FirstWeek.DayOfWeek = DofWeek Then
NewDay = d
Exit For
End If
Next
Dim DaysToAdd = (OfInputMonth - 1) * 7
newDate = New Date(NewYear, NewMonth, NewDay).AddDays(DaysToAdd)
Dim NewDateString = $"{newDate.ToString("MM/dd/yyyy")} is the {GetOrdinalString(OfInputMonth)} {DofWeek} of {TempDate.ToString("MMMM")}, {TempDate.Year}"
Return NewDateString
End Function
Private Function GetOrdinalString(input As Integer) As String
Dim output As String
Select Case input
Case 1
output = "1St"
Case 2
output = "2nd"
Case 3
output = "3rd"
Case 4
output = "4th"
Case 5
output = "5th"
Case Else
output = ""
End Select
Return output
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim InputDate As Date
Dim MonthsToAdd As Integer
If Not Date.TryParse(TextBox1.Text, InputDate) Then
MessageBox.Show("Please enter a valid date in Date")
Return
End If
If Not Integer.TryParse(TextBox2.Text, MonthsToAdd) Then
MessageBox.Show("Please enter a valid number in Months To Add")
Return
End If
Dim d = NdNwk(InputDate, MonthsToAdd)
MessageBox.Show(d)
End Sub
First of all, thanks for all the feedback.
The solution that I was able to parse together is as follows:
A text box to show the number of months.
A text box to show the new date.
A button click action to run the following code:
Private Sub BtnMonth_Click(sender As Object, e As EventArgs) Handles BtnMonth.Click
Dim WrkDt As Date = Now
Dim QtyMnths As Integer = CType(TxtMntCount.Text, Int32)
Dim newFoM = New Date(WrkDt.Year, WrkDt.Month, 1).AddMonths(QtyMnths)
Dim DoWDt As Integer = WrkDt.DayOfWeek
Dim newMntdate = newFoM.AddDays(Enumerable.Range(0,
Date.DaysInMonth(newFoM.Year, newFoM.Month) - 1).Where(Function(i) newFoM.AddDays(i).DayOfWeek = DoWDt).Skip(1).First())
TxtNewDate.Text = Format(newMntdate, "MMMM dd, yyyy (ddd)")
End Sub
This works perfectly fine for me!
Mary's solution looks great, and I will give it a shot in the future when I need a modular input.
Thanks again for all the help!
I tested your solution, and it doesn’t produce the described results.
See test and correct solution at: https://dotnetfiddle.net/v5wGng
A couple of things from your original problem, you should prefer calculation to loops wherever possible, and you should use the required types wherever possible. If you have date in one format (string) and need it in another for your calculations, you should do the conversion and then call a function that does your calculations where all of the parameters are of the correct type.
Public Function GetSameWeekAndWeekDay(dt as date, months as integer) as Date
Dim newMonth =(new date(dt.year, dt.month, 1)).AddMonths(Months)
Dim week = getweek(dt)
Dim sameWeekDay = GetNthDayOfWeek(newMonth, week, dt.DayOfWeek)
Return SameWeekday
End Function
Public Function GetWeek(dt as date) as integer
Return(dt.day - 1) \ 7
End Function
Public Function GetNthDayOfWeek(dt as date, week as integer, weekDay as System.DayofWeek) as Date
Dim first = new Date(dt.year, dt.month, 1)
Dim baseDate = first.AddDays(-(first.DayOfWeek - system.dayofweek.Sunday))
Dim newDate = baseDate.AddDays((week * 7) + weekday)
If(newdate.DayOfWeek < first.DayOfWeek) then
newDate = newDate.AddDays(7)
End If
Return newdate
End Function

Create time duration from date time picker

I am creating a VB Class - Employees work time for a single shift which occurs during one working day. does not cross midnight, with breaks of total duration but no specified time . It has 3 date/time pickers Start Time, Finish Time, Break duration time. I want to deduct start time from finish time and deduct break duration to give total time worked. Formatted HH:MM I am going wrong somewhere but cannot put my finger on it, could you please help.
Dim TimeIn As Date = StartTime.Value
Dim TimeOut As Date = FinishTime.Value
Dim Break As Date = BreakPicker.Value
Dim TimeNow As Date = DateTime.Now
Dim TempTime As Date = TimeNow + Break
Dim BreakDuration As System.TimeSpan = TempTime - TimeNow
Dim diff As System.TimeSpan = TimeOut.Subtract(TimeIn)
Dim diff1 As System.TimeSpan = TimeOut - TimeIn
Dim diff2 As Integer = ((TimeOut - BreakDuration) - TimeIn).TotalMinutes
Dim diff3 As System.TimeSpan = TimeNow.Subtract(TimeOut)
If TimeOut <= TimeIn Then
MsgBox("Invalid time")
Exit Sub
End If
Dim TotMins As Integer = diff2
Dim Hours As Integer = Math.Floor(TotMins / 60)
Dim Minutes As Integer = TotMins Mod 60
HoursRequiredBox.Text = (Hours & "h : " & Minutes & "m".ToString())
I would do it by accessing the properties of the datepicker.
So for hours, you can use:
Dim hour1 As Integer = 0
Dim hour2 As Integer = 0
Dim hourTotal As Integer = 0
hour1 = datepicker1.value.hour
hour2 = datepicker2.value.hour
hourTotal = hour2 - hour1
Same goes for the minute. Just replace .hour to .minute

Calculate 2 dates excluding weekends VB net

I'm trying compute the dates of Due date into Date Returned. And if the date return pass the due date in one day. there will be a fine.
This is my code in computation
Dim st As Integer = MetroDateTime1.Value.Date.Subtract(Label9.Text).Days
If (Label6.Text) > (MetroDateTime1.Value.Date) Then _
MessageBox.Show("Date return must not below to date borrowed", _
"Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
MetroDateTime1.Focus()
ElseIf (st > 0) Then
MetroTextBox7.Text = (st * 5).ToString()
Else
MetroTextBox7.Text = 0
End If
'Metrotextbox7 is the textbox for fines. But, how to compute the dates excluding the weekends?
'get business Days
Public Shared Function GetBusinessDays(startDay As DateTime, endDay As DateTime) As Integer
Dim today = Date.Today
Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim businessDays =
From d In Enumerable.Range(0, (endDay.Date - startDay.Date).Days + 1)
Select day = today.AddDays(d)
Where Not weekend.Contains(day.DayOfWeek)
Return businessDays.Count()
End Function
already answered question

Array of Workdays

I am looking for a way to store the last workday of each month between two "Input dates", and I need to store them as Strings in an array. I have tried to use the Worksheet function "Workday", but my input dates are of the format dd-mm-yyy, and I coundn't get it to work..
Any help is appreciated, Thanks.
Too bad, i've assumed that your VB.NET tag was the correct one, now it's removed. However, if someone needs something similar in .NET this might be helpful:
Dim fromDate = DateTime.Today.AddYears(-1) ' sample days
Dim toDate = DateTime.Today
Dim startDay = New Date(fromDate.Year, fromDate.Month, 1).AddMonths(1)
Dim endDay = New Date(toDate.Year, toDate.Month, 1).AddMonths(1)
Dim monthsBetween As Int32 = GetMonthsBetween(startDay, endDay)
Dim nonWorkingDays = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim workingDatesBetween As New List(Of String)
For month As Int32 = 0 To monthsBetween
Dim d As DateTime = startDay.AddMonths(month)
' look into last months last days, shorter way
Dim lastWorkingDay As Date = Date.MinValue
While lastWorkingDay = Date.MinValue
d = d.AddDays(-1) ' look backwards into the last month to find the last working-day
If Not nonWorkingDays.Contains(d.DayOfWeek) Then
lastWorkingDay = d
workingDatesBetween.Add(lastWorkingDay.ToString("dd-MM-yyy", CultureInfo.InvariantCulture))
End If
End While
Next
Dim result = workingDatesBetween.ToArray()
This method was used to determine the number of months between two dates:
Public Shared Function GetMonthsBetween(date1 As DateTime, date2 As DateTime) As Int32
Dim months = Math.Abs(((date1.Year - date2.Year) * 12) + date1.Month - date2.Month)
Return months
End Function
or as reusable method (although i doubt that someone needs this method often):
Public Shared Function GetLastWorkingDatesInMonthBetween(fromDate As Date, toDate As Date) As Date()
Dim startDay = New Date(fromDate.Year, fromDate.Month, 1).AddMonths(1)
Dim endDay = New Date(toDate.Year, toDate.Month, 1).AddMonths(1)
Dim monthsBetween As Int32 = GetMonthsBetween(startDay, endDay)
Dim nonWorkingDays = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim workingDatesBetween As New List(Of Date)
For month As Int32 = 0 To monthsBetween
Dim d As DateTime = startDay.AddMonths(month)
' look into last months last days, shorter way
Dim lastWorkingDay As Date = Date.MinValue
While lastWorkingDay = Date.MinValue
d = d.AddDays(-1) ' look backwards into the last month to find the last working-day
If Not nonWorkingDays.Contains(d.DayOfWeek) Then
lastWorkingDay = d
workingDatesBetween.Add(d)
End If
End While
Next
Return workingDatesBetween.ToArray()
End Function
Now you get the String() from the Date() via Array.ConvertAll:
Dim allNonWorkingDates = GetLastWorkingDatesInMonthBetween(DateTime.Today.AddYears(-1), DateTime.Today)
Dim result As String() = Array.ConvertAll(allNonWorkingDates, Function(d) d.ToString("dd-MM-yyy", CultureInfo.InvariantCulture))
Result with the sample year above:
30-09-2013
31-10-2013
29-11-2013
31-12-2013
31-01-2014
28-02-2014
31-03-2014
30-04-2014
30-05-2014
30-06-2014
31-07-2014
29-08-2014
30-09-2014