Days in a certain month - vb.net

I want to calculate how many days there are in a month. Obviously if there is a leap year then February would have 29 days.
I have some code that works out if it a leap year or not, but I do not know if it is useful.
I tried to do the current year and to count the days of the month that is entered; however there's an error and I'm not sure what to do.
Sub daysInMonth()
Console.WriteLine("Please Enter month you will like to calculate number of days: ")
Dim inputMonth As DateTime = Console.ReadLine()
Dim newMonth = DateAndTime.Month(inputMonth)
Dim current = Now()
Dim currentYear = (Year(current))
Dim febuaryLeapYear = System.DateTime.DaysInMonth(currentYear, newMonth)
End Sub
Solved

I have this function which returns the number of days in any month, any year. Hope helps
Private Function Dates(ByVal Year As Integer, Month As Integer) As Integer
Return DateTime.DaysInMonth(Year, Month)
End Function

I think the problem in this case is that DaysInMonth requires the month to be expressed as an integer. So if you change inputMonth to Integer, you shouldn't receive an error.

Integer.TryParse(string, integerVariable) will check the string to see if it can be converted to an Integer. It will return True or False so it can be used in an If statemnent. In addition it fills the integerVariable with the Integer representation of the string.
The AndAlso parts of the If will never execute if the previous condition is false. This is called short circuiting. Your code will not blow up comparing numbers in the AndAlso conditions because if the first part is false it never executes.
Sub CalculateDaysInMonth() 'It is a bad idea to name your Sub the same as a .net method
Do 'The method will loop until the user enters correct data
'A more explicit message will help user to enter correct data
Console.WriteLine("Please enter a month by entering a number between 1 and 12")
Dim inputMonth As Integer
If Integer.TryParse(Console.ReadLine, inputMonth) AndAlso inputMonth > 0 AndAlso inputMonth < 13 Then
Dim currentYear As Integer = Now.Year
Dim numberOfDays As Integer = DateTime.DaysInMonth(currentYear, inputMonth)
'This is an interpolated string. If your version doesn't support this you can use String.Format
'String.Format("There are {0} in month {1} this year", numberOfDays, inputMonth)
Console.WriteLine($"There are {numberOfDays} in month {inputMonth} this year")
Return
End If
Loop
End Sub

Related

Find the day given date and number of days

Am looking a function that would aid me to auto detect due date when duration period number is entered in duration textbox.Am having challenge since all the months do not end with same date number i.e. 31 as some end on 30.
NOTE: The function should be able to automatically calculate up to next year if lets say user inputs 3 while in November 2018 its means the duration period will go up January 2019
See the picture below
Dim start_date As Date = dtpStart.Value
Dim totalDays As Integer = 3 * 30
Dim ts As TimeSpan = start_date.Add(totalDays)
Dim end_date As Date = ts
I have tried the above but its giving me an error "value of type integer can not be converted to system.TimeSpan."
If i understand you correctly, if a user enters 3 you want to advance 3 times 30 days later from the start_date.
Dim start_date = dtpStart.Value
Dim end_date = start_date.AddDays(3* 30)
In terms of a function, you could have:
private function AddDays(Byval start_date as Date, Byval amount as integer) as Date
Dim end_date = start_date.AddDays(amount)
return end_date
end function
The usage would be:
Dim new_date = AddDays(dtpStart.Value, 3*30)

How to determine week number within calendar quarter period VB6

Having some trouble locating a function to determine the week number of a quarter period in a standard date based (i.e. Day 1 = 2017-01-01) calendar table.
My table has the following information stored :
Quarter Number, Beginning Date, End Date, Number of Days;
As an example, for the first quarter of calendar year, the result for Week 1 would be 1, Week 14 would be 1, going through each quarter until the final week of quarter 4.
Any ideas please help?
I don't believe there is a built-in function for this. If I understand what you're asking, this is a trivial function to write. You don't include any code so I'm just giving you the most basic example. You want to do something similar to this.
Public Function GetWeekInQuarter(ByVal WeekNumber As Integer) As Integer
Const intWeeksInQuarter = 13
Dim intResult As Integer
intResult = WeekNumber Mod intWeeksInQuarter
'if intResult <> intWeeksInQuarter = 0 then this is the 13th week
GetWeekInQuarter = IIf(intResult <> intWeeksInQuarter, intResult, intWeeksInQuarter)
End Function

Calculate X amount of hrs ahead only counting 9-5 hrs

I'm trying to get a quick ETA on some pre-determined values, 16 and 40. So for example, I need my code to quickly calculate an ETA on an item if it takes 16 hours, but only count the 9-5 (8) hours per day. Obviously I'd need to include the remaining hours of that day, which I have in the code snipped below. However I'm giving myself an ofly sore head trying to work out the best way to proceed with the code. Perhaps someone's got a good idea?
Dim TargetTime as Integer = 16
Dim currentHr As Integer = current.Hour
Dim TodaysRemainingHours As Integer = 0
If currentHr >= 9 AndAlso currentHr < 17 Then
'Count remaining hours
TodaysRemainingHours = (17- currentHr)
Else
'Dont count today
TodaysRemainingHours = 0
End If
My plan is:
TargetTime - TodaysRemainingHours --- Gives the value to count
to.
Somehow calculate the hours based on 9-5 time spans only.
Display lblOutput as: "ETA: 2pm 25/11/2016"
As you can see I know how to get the vaule I need to count to, but I need some help with firstly only counting the hours in each day from 9-5 and then returning the actual hour estimated. This isn't for anything profitable, it's a personal ETA program.
Thank you topshot, your comment helped me work it out! The below code seems to work for me, I haven't identified any issues anyway. I had to make sure I wasn't counting the remaining hours in the current day if the time is past 5pm as well. Thank you.
Dim TargetTime As Integer = 16
Dim current As Datetime = DateTime.now
Dim currentHr As Integer = current.Hour
Dim TodaysRemainingHours As Integer = 0
If currentHr >= 9 AndAlso currentHr < 17 Then
'Count remaining hours
TodaysRemainingHours = (17 - currentHr)
Else
'Dont count today
TodaysRemainingHours = 0
End If
If currentHr >= 9 AndAlso currentHr < 17 Then
'Deduct todays hours from target time.
TargetTime = (TargetTime - TodaysRemainingHours)
'Display results
MsgBox("ETA: " & Now.AddDays(TargetTime / 8))
Else
'Skip todays hours and count from tomorrow morning at 9am
Dim Tomorrow As DateTime = Today.AddDays(1)
Dim TomorrowMorning As TimeSpan = new TimeSpan(09, 00, 0)
Tomorrow = Tomorrow.Date + TomorrowMorning
'Display results
MsgBox("ETA: " & Tomorrow.AddDays(TargetTime / 8))
End If

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

Return the correct number of weeks in a year

In a previous question I asked the community for support on how to display a week based on the requested week number. That question has now evolved into a question of how to display the correct number of weeks in a year.
I've started with this method based on input I've gotten from other threads within the StackExchange network, yet it displays the wrong week value.
Protected Friend Shared Function GetNumberOfWeeksInAYear(ByVal GetYear As Nullable(Of Integer)) As Nullable(Of Integer)
Dim RequestedYear As DateTime = New DateTime(GetYear, 12, 31)
Return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(RequestedYear, CalendarWeekRule.FirstFourDayWeek, FirstDayOfWeek.System)
End Function
The year parameter represents the requested year (as an integer) and the return value is also a integer representing the return number of weeks. This method is used to set navigational buttons in a custom calendars week view I'm building.
Now for some testing. 2003 had 52 weeks while 2004 had 53 weeks. I've confirmed this by comparing various calendars. The code above though returns 53 for 2003 and 52 for 2004. I've tried to add a year to the input but it won't change the output.
How should I improve the method to get it to output the correct week value?
Public Shared Function NumberOfWeeks(dateFrom As DateTime, dateTo As DateTime) As Integer
Dim Span As TimeSpan = dateTo.Subtract(dateFrom)
If Span.Days <= 7 Then
If dateFrom.DayOfWeek > dateTo.DayOfWeek Then
Return 2
End If
Return 1
End If
Dim Days As Integer = Span.Days - 7 + CInt(dateFrom.DayOfWeek)
Dim WeekCount As Integer = 1
Dim DayCount As Integer = 0
WeekCount = 1
While DayCount < Days
DayCount += 7
WeekCount += 1
End While
Return WeekCount
End Function
You should turn on Option Strict as you are passing a wrong type to Calendar.GetWeekOfYear:
GetWeekOfYear(Integer theYear, rule As System.Globalization.CalendarWeekRule,
firstDayOfWeek As System.DayOfWeek)
The last parameter, System.DayOfWeek, is not the same thing as the FirstDayOfWeek enumeration in the VisualBasic NameSpace. The VB one is for use with the VB DateAndTime Type, not the Net DateTime type. When you turn on Option Strict, the compiler complains about the type mismatch.
This uses the "sv-SE" culture to get the week count for the various rules:
Dim cult = CultureInfo.CreateSpecificCulture("sv-SE")
Dim cal As Calendar = cult.Calendar
' First Day
Console.WriteLine("{0} - {1}", CalendarWeekRule.FirstDay.ToString,
cult.Calendar.GetWeekOfYear(RequestedYear,
CalendarWeekRule.FirstDay,
cult.DateTimeFormat.FirstDayOfWeek).ToString)
' first four day
Console.WriteLine("{0} - {1}", CalendarWeekRule.FirstFourDayWeek.ToString,
cult.Calendar.GetWeekOfYear(RequestedYear,
CalendarWeekRule.FirstFourDayWeek,
cult.DateTimeFormat.FirstDayOfWeek).ToString)
' first full week
Console.WriteLine("{0} - {1}", CalendarWeekRule.FirstFullWeek.ToString,
cult.Calendar.GetWeekOfYear(RequestedYear,
CalendarWeekRule.FirstFullWeek,
cult.DateTimeFormat.FirstDayOfWeek).ToString)
' WRONG - requires Option Strict OFF - VB enum
Console.WriteLine("{0} - {1}", "VB FirstDayOfWeek Enum",
cult.Calendar.GetWeekOfYear(RequestedYear,
CalendarWeekRule.FirstFullWeek, FirstDayOfWeek.System).ToString)
The output:
FirstDay - 53
FirstFourDayWeek - 53
FirstFullWeek - 52
VB FirstDayOfWeek Enum - 52
The way you probably want to use it:
' just to make things shorter
Dim cult = CultureInfo.CurrentCulture
Return cult.Calendar.GetWeekOfYear(RequestedYear,
CalendarWeekRule.FirstDay,
cult.DateTimeFormat.FirstDayOfWeek)
The net result is that you were forcing the calendar to always use Sunday as the first Day of Week rather than Monday as defined in DateTimeFormat for the sv-SE culture.