How to convert a date into yyww & vice versa in VB.NET? - vb.net

Would anyone know how to convert any date first into a Saturday and then into yyww (weekyear) in VB.NET?
And vice versa, ie yyww into a Saturday?

Dim d As DateTime = #1/20/2009#
d = d.AddDays(DayOfWeek.Saturday - d.DayOfWeek)
Dim myCal As New System.Globalization.GregorianCalendar
Dim wkOFyr As Integer = myCal.GetWeekOfYear(d, _
Globalization.CalendarWeekRule.FirstDay, _
DayOfWeek.Sunday)
Dim s As String
s = d.ToString("yy") & wkOFyr.ToString.PadLeft(2, "0"c)

Assuming your weeks start on Sunday, you could probably do something like this to get the saturday of the current week:
Dim daysToAdd As Integer = DayOfWeek.Saturday - yourDate.DayOfWeek
Dim dateSaturday as Date = yourDate.AddDays(daysToAdd)
I didn't test it though.
Then you could get the weekyear by doing something like:
Dim weekYear As Integer = CInt(Math.Ceiling(dateSaturday.DayOfYear / 7))
Using the reverse logic you can find the saturday corresponding to the weekyear.

Related

Strange Date Parsing Results

I am trying to make a small helper app to assist in reading SCCM logs. Parsing the dates has been pretty straightforward until I get to the timezone offset. It is usually in the form of "+???". literal example: "11-01-2016 11:44:25.630+480"
DateTime.parse() handles this well most of the time. But occasionally I run into a time stamp that throws an exception. I cannot figure out why. This is where I need help. See example code below:
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = "11-07-2016 16:43:51.541+600"
Dim dateStr_B As String = "11-01-2016 11:44:25.630+480"
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
IF run it would seem dateStr_B is an invalid time stamp? Why is this? I've tried to figure out how to handle the +480 using the 'zzz' using .ParseExact() format as shown here Date Formatting MSDN
Am I missing something with the timezone offset? I've searched high and low but these SCCM logs seem to use a non standard way of representing the offset. Any insight would be greatly appreciated
The problem is that +480 is indeed an invalid offset. The format of the offset from UTC (as produced when using the "zzz" Custom Format Specifier) is hours and minutes. +600 is 6 hours and 0 minutes ahead of UTC, which is valid. +480 would be 4 hours and 80 minutes ahead of UTC, which is invalid as the number of minutes can't be more than 59.
If you have some external source of date and time strings that uses an offset that is simply a number of minutes (i.e. +600 means 10 hours and +480 means 8 hours), you will need to adjust the offset before using DateTime.Parse or DateTime.ParseExact.
[Edit]
The following function takes a timestamp with a positive or negative offset (of any number of digits) in minutes, and returns a DateTime. It throws an ArgumentException if the timestamp is not in a valid format.
Public Function DateTimeFromSCCM(ByVal ts As String) As DateTime
Dim pos As Integer = ts.LastIndexOfAny({"+"c, "-"c})
If pos < 0 Then Throw New ArgumentException("Timestamp must contain a timezone offset", "ts")
Dim offset As Integer
If Not Integer.TryParse(ts.Substring(pos + 1), offset) Then
Throw New ArgumentException("Timezone offset is not numeric", "ts")
End If
Dim hours As Integer = offset \ 60
Dim minutes As Integer = offset Mod 60
Dim timestamp As String = ts.Substring(0, pos + 1) & hours.ToString & minutes.ToString("00")
Dim result As DateTime
If Not DateTime.TryParse(timestamp, result) Then
Throw New ArgumentException("Invalid timestamp", "ts")
End If
Return result
End Function
Thank you for the insight. I had a feeling I would need to handle this manually. I just wanted to make sure I wasn't missing something simple in the process. My knowledge of the date and time formatting is a bit lacking.
As such, I have altered my code so that it handles the offset. Granted I will have to add some more input validation in the final product.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = correctOffset("11-07-2016 16:43:51.541+600")
Dim dateStr_B As String = correctOffset("11-07-2016 16:43:51.541+480")
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
End Sub
Public Function correctOffset(ByVal ts As String)
Dim offset As Integer = CInt(ts.Substring(ts.Length - 3))
Dim offHour As Integer = offset / 60
Dim offMin As Integer = offset - (offHour * 60)
Dim strhour As String = Nothing
Dim strmin As String = Nothing
If offHour <= 9 Then
strhour = "0" & CStr(offHour)
Else
strhour = CStr(offHour)
End If
If offMin <= 9 Then
strmin = "0" & CStr(offMin)
Else
strmin = CStr(offMin)
End If
Return ts.Substring(0, ts.Length - 3) & strhour & ":" & strmin
End Function

VB.NET - How do I find difference in dates in MM/DD format?

If I have two dates
Dim date1 As String = 01/05
Dim date2 As String = 01/07
Dim date As Integer
Date = 2
How do I go about making sure that 2 handles month changes and just general dates in this format?
You would parse the strings into DateTime values, then you can subtract them to get a TimeSpan value that is the difference. Use the Days property to get the whole days from the value:
Dim date1 As String = "01/05"
Dim date2 As String = "01/07"
Dim d1 = DateTime.ParseExact(date1, "MM'/'dd", CultureInfo.InvariantCulture)
Dim d2 = DateTime.ParseExact(date2, "MM'/'dd", CultureInfo.InvariantCulture)
Dim date As Integer = (d2 - d1).Days

Calculating days to a specific date

Dim intYear, intMonth, intDay As Integer, strResult As String, tspResult As TimeSpan
intYear = Integer.Parse(txtYear.Text)
intMonth = Integer.Parse(txtMonth.Text)
intDay = Integer.Parse(txtDay.Text)
Dim dteDatum As New System.DateTime(intYear, intMonth, intDay)
tspResult = Now.Subtract(dteDate)
strResult = Math.Abs(tspResult.Days).ToString
MessageBox.Show(strResult)
For example:
today it is the 1st of october and i want to know how many days till the 4th of october.
The program will say 2days but that's wrong, it must be 3 days.
How can i fix this?
(Calculations in the past are good)
Thanks in advance and sorry if my english sucks.
Try use datediff
' The following statements set datTim1 to a Thursday
' and datTim2 to the following Tuesday.
Dim datTim1 As Date = #1/4/2001#
Dim datTim2 As Date = #1/9/2001#
' Assume Sunday is specified as first day of the week.
Dim wD As Long = DateDiff(DateInterval.Weekday, datTim1, datTim2)
Dim wY As Long = DateDiff(DateInterval.WeekOfYear, datTim1, datTim2)

If date is (certain date) then

How would I make my application do an event when there is a certain date? I can't seem to find something that works. Year doesn't matter, just day and month is all I need.
Since day and month is all you want to match on:
Dim myDate As Date = Date.Now
Dim someMonth As Integer = 4
Dim someDay As Integer = 13
If myDate.Month = someMonth AndAlso myDate.Day = someDay Then
... month and day are matched
End If
Use IsDate....
If IsDate(MyDate) Then.....
Update various ways of defining date
'DateTime constructor: parameters year, month, day, hour, min, sec
Dim MyDate1 As New Date(2012, 12, 10, 12, 0, 0)
'initializes a new DateTime value
Dim MyDate2 As Date = #12/10/2012 12:00:52 AM#
'using properties
Dim MyDate3 As Date = Date.Now
Dim MyDate4 As Date = Date.UtcNow
Dim MyDate5 As Date = Date.Today
Try something like this:
Dim thisDate As Date = New Date(2014, 4, 13) ' Assuming this is provided
Dim certainDate As Date = New Date(2013, 4, 13) ' Assuming this is provided
If thisDate = New Date(thisDate.Date.Year, certainDate.Month, certainDate.Day) Then
Debug.Print("dates equal excluding year")
Else
Debug.Print("dates UNequal excluding year")
End If
Rememebr, this will always create a new date object for comparison but it works.
Hope it helps!

How use loops by datetime each on weekly in vb.net

i try loop while with datetime each on weekly in VB.NET 2008.
This Code
Private Sub Button1_Click()....
'Select DateTime
Dim strDate As Date = dateTimePicker.Value.ToString("yyyy-MM-dd")
'one week (+7)
Dim strDateWeek As String = DateAdd("d", +7, dateTimePicker.Value.ToString("yyyy-MM-dd"))
'DateCurrent
Dim strDateNow As String = DateAdd("d", 0, Now.ToLongDateString())
'While strDate < strDateNow
'ListBox1.Items.Add(strDateWeek)
'End While
ListBox1.Items.Add(strDateWeek)
End Sub
Example
I select on datetimepicker at "04/02/2013"
Output now: 11/02/2013
But I need Output each on weekly
11/02/2013
18/02/2013
25/02/2013 >>> To Current Week
I try loop While, But don't work.
Thanks you for your time. :)
You could do a while loop until the datetime is greater than today?
You want to use DateTime rather than Date, so you can compare to a DateTime.Now
You want to set your actual DatePicker value to a variable, else it will always be the same and you will just get an infinite loop.
Dim datePickerValue As DateTime = DateTimePicker.Value
Dim strDate As Date = DateTimePicker.Value.ToString("yyyy-MM-dd")
Dim strDateWeek As String
Dim strDateNow As String = DateAdd("d", 0, Now.ToLongDateString())
While datePickerValue < DateTime.Now()
strDateWeek = DateAdd("d", +7, datePickerValue.ToString("yyyy-MM-dd"))
datePickerValue = DateAdd("d", +7, datePickerValue.ToString("yyyy-MM-dd"))
ListBox1.Items.Add(strDateWeek)
End While
Just done it on my VS using your naming conventions and this works fine for me
It's been a long time since I didn't have used VB, but maybe I can help?
In your code, using while could be a wrong choice perhaps you could use a for with a break instead.
for I = 1 to 10
Dim strDateWeek As String = DateAdd("d", +7 * i, dateTimePicker.Value.ToString("yyyy-MM-dd"))
.
.
.
or
while(...)
I += 1
Dim strDateWeek As String = DateAdd("d", +7 * i, dateTimePicker.Value.ToString("yyyy-MM-dd"))
Hope that helps.
Try this:
Dim dtAux As Date = dateTimePicker.Value
Dim dtEnd As Date = Date.Today.AddDays(7 - dt.DayOfWeek)
While dtAux <= dtEnd
ListBox1.Items.Add(dtAux.ToString("yyyy-MM-dd"))
dtAux = dtAux.AddDays(7)
End While
The date dtEnd is the last day of the current week, if you want the loop to stop on the current date simply change the while condition to:
While dtAux <= Date.Today