Vb.net Current Date minus Date - vb.net

lets say that my date is:
Dim theDate As DateTime = DateTime.ParseExact("2013-04-10 21:34 PM", "yyyy-MM-dd HH:mm tt", CultureInfo.InvariantCulture)
im using this format:
"yyyy-MM-dd HH:mm tt"
i want to get the current date and do somthing like:
Dim theDate As DateTime = DateTime.ParseExact("2013-04-10 21:34 PM", "yyyy-MM-dd HH:mm tt", CultureInfo.InvariantCulture)
Dim currentTime As System.DateTime = System.DateTime.Now
dim Result as new datetime
Result = currentTime.Date - theDate
Update:
i tried:
Dim currentTime As System.DateTime = System.DateTime.Now
Dim date1 As New System.DateTime(2013, 4, 10, 21, 34, 10)
Dim date2 As New System.DateTime(currentTime.Year, currentTime.Month, currentTime.Day, currentTime.Hour, currentTime.Minute, currentTime.Second)
Dim diff1 As System.TimeSpan
diff1 = date2.Subtract(date1)
MsgBox(diff1.ToString)

A TimeSpan will allow you to subtract dates.
DateTime.Subtract Method (TimeSpan)
Dim date1 As New System.DateTime(1996, 6, 3, 22, 15, 0)
Dim date2 As New System.DateTime(1996, 12, 6, 13, 2, 0)
Dim diff1 As System.TimeSpan
' diff1 gets 185 days, 14 hours, and 47 minutes.
diff1 = date2.Subtract(date1)
MsgBox(diff1.Days)
MsgBox(diff1.Hours)
MsgBox(diff1.Minutes)
Here are all the members of the TimeSpan class

Related

How to change date in IF statement

I wish to change startDate depending on the day of the week. Here is what I've tried, the error I get is BC30311: Value of type 'Integer' cannot be converted to 'Date'.
Dim curr As Date = Date.Now
Dim day As String = Date.Today.DayOfWeek.ToString()
Dim startTime As New Date
If day="saturday" Then
startTime=(curr.Year, curr.Month, curr.Day, 17, 0, 0)
Else
startTime=(curr.Year, curr.Month, curr.Day, 13, 0, 0)
End If
Dim endTime As New Date(curr.Year, curr.Month, curr.Day, 21, 59, 0)
If (curr >= startTime) And (curr <= endTime) Then
'''Some Code
I simply need to change startDate to 13:00 hours for Saturdays. Any help appreciated
This is a better way to write code to do what you appear to want to do:
Dim currentDay = Date.Today
Dim startTime = currentDay.AddHours(If(currentDay.DayOfWeek = DayOfWeek.Saturday, 17, 13))
Dim endTime = currentDay.AddHours(21).AddMinutes(59)
Dim currentTime = Date.Now
If currentTime >= startTime AndAlso currentTime <= endTime Then

Fun Logic to minus date with date and get the diffdate vb.net

Ok I cannot think of a algorithm to do this using vb.net.
so here is the 3 variable
Dim DateFrom as date = '01/09/2015'
Dim DateNow as date = Date.Now
Dim Holiday() as date '' <-- List of holiday dates
So what I want to do is I want to get the "Day" diffdate From DateFrom and DateNow and excluding the minus the date in the Holiday() array and also saturday Sunday.
so let say my DateFrom is '01/09/2015' which is Tuesday and my
DateNow is '09/09/2015' which is also tuesday and inside the Holiday() array there's '4/09/2015' Friday. the output of diffdate is suppose to be 5 Day since since (DateNow ---Difference Day minus Holiday()array and also minus saturday and sunday -- DateFrom)
I scratches my head about 152.5 times and still cannot find the way to do this.
I think you can solve this problem using something like this:
Dim intTotalDays As Integer = 0
Dim dtStartDate As New DateTime(2015, 10, 1)
Dim dtEndDate As New DateTime(2015, 10, 31)
Dim Holidays As DateTime() = {
New DateTime(2015, 10, 15),
New DateTime(2015, 10, 17)
}
For i As Integer = 0 To DateDiff(DateInterval.Day, dtStartDate, dtEndDate)
Dim dtDay As DateTime = DateAdd(DateInterval.Day, i, dtStartDate)
If Not dtDay.DayOfWeek = DayOfWeek.Saturday And Not dtDay.DayOfWeek = DayOfWeek.Sunday And Not Holidays.Contains(dtDay) Then
intTotalDays += 1
End If
Next i
MsgBox(intTotalDays)
So you want to determine the number of working-days between two dates?
You can use following LINQ query:
Dim DateFrom As Date = #9/1/2015#
Dim Holiday() As Date = {#9/4/2015#}
Dim Weekend() As DayOfWeek = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim days As Int32 = (Date.Today - DateFrom).Days + 1 '+ 1 to include end day '
Dim workingDaysBetween =
From d In Enumerable.Range(0, days)
Let day = DateFrom.AddDays(d)
Where Not Weekend.Contains(day.DayOfWeek) AndAlso Not Holiday.Contains(day)
Dim countDays As Int32 = workingDaysBetween.Count()

VB.NET - Given a date, how can I get the date of last four fridays?

Given today's date want to get the date of the each Friday for the last four weeks.
Here is an easy LINQ approach:
Dim today = Date.Today
Dim lastFridays = From d In Enumerable.Range(0, Int32.MaxValue)
Let dt = today.AddDays(-d)
Where dt.DayOfWeek = DayOfWeek.Friday
Select dt
Dim lastFourFridays As Date() = lastFridays.Take(4).ToArray()
Since it's not the most efficient approach, here is a query that is still readable and maintainable but only searches the first friday and then takes only every 7th day:
Dim lastFriday = lastFridays.First() ' reuse of above query '
Dim fridays = From d In Enumerable.Range(0, Int32.MaxValue)
Let dt = lastFriday.AddDays(-d * 7)
Select dt
Dim lastFourFridays As Date() = fridays.Take(4).ToArray()
You may consume this one, which returns a list of such dates and excludes the one if the specifiedDate date is Friday:
Public Shared Function GetLastFourFridays(specifiedDate As DateTime) As List(Of DateTime)
Dim dtm As New List(Of DateTime)()
Dim dt As DateTime = specifiedDate
For i As Integer = 0 To 6
dt = dt.AddDays(-1)
If dt.DayOfWeek = DayOfWeek.Friday Then
dtm.Add(dt)
Exit For
End If
Next
dtm.Add(dt.AddDays(-7))
dtm.Add(dt.AddDays(-14))
dtm.Add(dt.AddDays(-21))
Return dtm
End Function
and the way you use it is:
Dim dtm As List(Of DateTime) = GetLastFourFridays(DateTime.Now)
For Each d As var In dtm
Console.WriteLine(String.Format("Date: {0}, Day: {1}", d.ToString(), [Enum].Parse(GetType(DayOfWeek), d.DayOfWeek.ToString())))
Next
Here is my way:
Function Last4Friday(ByVal StartDate As Date) As array
Dim L4F()
Dim mDate as date = StartDate
For value As Integer = 1 To 7
mDate = mDate.AddDays(-1)
If mDate.DayOfWeek = DayOfWeek.Friday Then
L4F = {mDate, mDate.AddDays(-7), mDate.AddDays(-14), mDate.AddDays(-21)}
exit for
End If
Next
Return L4F
End Function
Edit: If you need to check the inserted date and you want it returned in the array you may simply use:
Dim mDate as date = StartDate.AddDays(1)
instead of
Dim mDate as date = StartDate
Try this. It doesn't use a loop to find the starting Friday.
Dim someDate As DateTime = DateTime.Now
If someDate.DayOfWeek <> DayOfWeek.Friday Then
'do the math to get a Friday
someDate = someDate.AddDays(DayOfWeek.Friday - someDate.AddDays(1).DayOfWeek - 6)
End If
Dim last4Fridays As New List(Of DateTime) From {someDate, someDate.AddDays(-7), someDate.AddDays(-14), someDate.AddDays(-21)}
All of the other suggestions have used a loop to find the starting Friday. If this code is used infrequently then how the starting Friday is determined might not matter.
edit: as function
Function FindLastFourFridays(someDate As DateTime) As List(Of DateTime)
'Find first Friday to include
If someDate.DayOfWeek <> DayOfWeek.Friday Then
someDate = someDate.AddDays(DayOfWeek.Friday - someDate.AddDays(1).DayOfWeek - 6)
' uncomment these two lines if you do not want initial someDate.DayOfWeek = DayOfWeek.Friday to be included
'Else
' someDate = someDate.AddDays(-7)
End If
'build the return (four fridays)
Dim last4Fridays As New List(Of DateTime) From {someDate, someDate.AddDays(-7), someDate.AddDays(-14), someDate.AddDays(-21)}
Return last4Fridays
End Function
This function does not need to be passed a date it picks up today's date and gets the last four Friday's from today. It can be changed around to get any day of the week.
Dim todaysDate As Date = Date.Today
Dim oldDay As Integer
Dim thisWeek As Date
Dim firstWeek As Date
Dim secondWeek As Date
Dim thirdWeek As Date
Dim fourthWeek As Date
'finds the Friday of the end of the current week No mattter what day you are working
Dim daycount As Integer
'use this to check specific dates "Dim datetime As New DateTime(2015, 4, 13)"
oldDay = Weekday(todaysDate)
thisWeek = todaysDate
If oldDay < 6 Then
daycount = 6 - oldDay
thisWeek = thisWeek.AddDays(+daycount)
ElseIf oldDay > 6 Then
daycount = oldDay - 6
thisWeek = thisWeek.AddDays(-daycount)
End If
Dim currentDate As Date = Now
Do While Not currentDate.DayOfWeek = DayOfWeek.Friday
currentDate = currentDate.AddDays(-1)
Loop
fourthWeek = currentDate.AddDays(-21)
thirdWeek = currentDate.AddDays(-14)
secondWeek = currentDate.AddDays(-7)
firstWeek = currentDate

VB.net Get total time between two time spans

I was wondering if there is a function with VB.NET that can tell me the total time that two different time spans have in common.
for example, I have these two different time spans:
1st Date : (2013-01-01 8:30 AM) - (2013-01-01 11:30PM)
2nd Date : (2013-01-01 10:00 PM) - (2013-01-02 6:00 AM)
Can VB.NET tell me that the answer is 1 hour and 30 mins? (perhaps in decimal)
It is 1 hour and 30 minutes because up to 10:00PM in the evening and 11:30 in the evening falls in with the other time span.
Summary:
I just need a function that will tell me how many hours in a certain timespan is a part of the night shift. (that's 10:00 PM to 6:00 AM).
This functionality is available to all .Net languages via the TimeSpan class:
eg.:
result = (dt2 - dt1).TotalHours
When you subtract two dates you get a TimeSpan.
The TotalHours property of the TimeSpan gives you the number of hours, or part thereof.
Check out the docs: http://msdn.microsoft.com/en-us/library/269ew577(v=vs.110).aspx
Date1 and Date2 represents the first time span and Date2 and Date3 represent the second time span. If the order of the dates are changed you will have to define an analogous else to the first if.
Dim date1 As Date = #1/1/2013 8:30:00 AM#
Dim date2 As Date = #1/1/2013 11:30:00 PM#
Dim date3 As Date = #1/1/2013 10:00:00 PM#
Dim date4 As Date = #1/2/2013 6:00:00 AM#
Dim timePeriod As TimeSpan
If date3.Date >= date1.Date And date3.Date <= date2.Date Then
If date4.Date <= date2.Date Then
timePeriod = date4.TimeOfDay - date3.TimeOfDay
Else
timePeriod = date2.TimeOfDay - date3.TimeOfDay
End If
End If
Msgbox(timePeriod.ToString)
EDIt: Just timePeriod = date4- date3 will convert the difference into timespan
EDIT 2:The code above would have returned date2-date3 even if there there was no common time span. The code below would return 0 in such a case. Also when comparing two Date variables in an If statement, the TimeOfDay part is neglected.
Dim date1 As Date = #1/1/2013 8:30:00 AM#
Dim date2 As Date = #1/1/2013 11:30:00 PM#
Dim date3 As Date = #1/1/2013 10:00:00 PM#
Dim date4 As Date = #1/2/2013 6:00:00 AM#
Dim timePeriod As TimeSpan
If date3 >= date1 And date3 <= date2 Then
If date4 <= date2 Then
timePeriod = date4 - date3
ElseIf date3 < date2 Then
timePeriod = date2 - date3
ElseIf date3.Date = date2.Date Then
If date3.TimeOfDay < date2.TimeOfDay Then
timePeriod = date2 - date3
Else
timePeriod = TimeSpan.FromDays(0)
End If
Else
timePeriod = TimeSpan.FromDays(0)
End If
End If
MsgBox(timePeriod.ToString)
EDIT:
Sorry, I misunderstood your question. I think this is what you are looking for.
Here is your DateRange class:
Public Class DateRange
Public Property StartTime As DateTime
Public Property EndTime As DateTime
Public ReadOnly Property NumberOfHours As Decimal
Get
Dim result As Double
result += (EndTime - StartTime).Hours
result += (EndTime - StartTime).Minutes / 60
result += (EndTime - StartTime).Seconds / 3600
Return result
End Get
End Property
End Class
This would be the C# function from the link, rewritten in VB:
Private Function GetIntersectionRange(range1 As DateRange, range2 As DateRange) As DateRange
Dim iRange As New DateRange()
iRange.StartTime = If(range1.StartTime < range2.StartTime, range2.StartTime, range1.StartTime)
iRange.EndTime = If(range1.EndTime < range2.EndTime, range1.EndTime, range2.EndTime)
If iRange.StartTime > iRange.EndTime Then iRange = Nothing
Return iRange
End Function
Here is a little snippet of code to do the calculation you asked and write the answer to the console:
Dim firstDate As New DateRange With {.StartTime = New DateTime(2013, 1, 1, 8, 30, 0), .EndTime = New DateTime(2013, 1, 1, 23, 30, 0)}
Dim secondDate As New DateRange With {.StartTime = New DateTime(2013, 1, 1, 22, 0, 0), .EndTime = New DateTime(2013, 1, 2, 6, 0, 0)}
Dim result As DateRange = GetIntersectionRange(firstDate, secondDate)
Console.WriteLine(result.NumberOfHours)
Like this?
Dim d1 As DateTime = "1/22/2018 8:30:00 AM"
Dim d2 As DateTime = "1/29/2018 5:30:00 PM"
Dim ts As TimeSpan = d2.Subtract(d1)
MessageBox.Show("Total Hours are " & Convert.ToDouble(Math.Round(ts.TotalHours, 2)))
Just play around with it

Date time validation in vb.net

Can anyone help me on how can I validate given DateTime between two DateTime using vb.net?
the given DateTime must not in between the two DateTime..
You can compare date instances the same way you would compare numbers as they override the LessThan, LessThanOrEqual, GreaterThan and GreaterThanOrEqual operators:
Dim minDate = New DateTime(2009, 4, 17)
Dim maxDate = New DateTime(2011, 4, 17)
Dim selectedDate = New DateTime(2010, 4, 17)
If selectedDate > minDate And selectedDate < maxDate Then
Console.WriteLine("selected date is valid")
Else
Console.WriteLine("selected date is invalid")
End If
Use DateTime.Compare
Dim date1 As New DateTime(100)
Dim date2 As New DateTime(200)
Dim workingDate As New DateTime(150)
If DateTime.Compare(workingDate , date1) >= 0 AND DateTime.Compare(workingDate , date2) <= 0 Then
Console.WriteLine("Between")
Else
Console.WriteLine("Not Between")
End If
Dim dt As Date = DateTimePicker1.Value.Date
If dt < CDate("2010-04-01") Or dt > CDate("2010-04-10") Then
MessageBox.Show("Date is not in the first 10 days of April so is ok")
End If