|
|
10 Aug 2007
|
Datetime Helper Functions in VB.Net Programming
In various forums, people often ask questions on simple date and time
conversion for use in their software development. Here are some helper functions in VB.
How to trim the time value from date
Function TrimTimeFromDate(ByVal d As DateTime) As DateTime Return DateTime.Parse(d.ToShortDateString) End Function
How to add time value to a date
' Usage newDateTimeVariable=AddTime(dateTimeVariable, "3:15")
Function AddTime (ByVal d As Date, ByVal hhmm As String) As Date Try Dim hh As Integer = 0 Dim mm As Integer = 0 If hhmm.IndexOf(":"c) > 0 Then hh = Integer.Parse(hhmm.Split(":")(0)) mm = Integer.Parse(hhmm.Split(":")(1)) Else mm = Integer.Parse(hhmm) End If If hh > 24 OrElse hh < 0 OrElse mm > 59 OrElse mm < 0 Then Throw New Exception End If Dim result As Date result = d.AddHours(hh) result = result.AddMinutes(mm) Return result Catch Throw New ApplicationException("Not a valid time") End Try End Function
How to Compare the time portion of two dates
You may want to find out some events which happens after a time of the day, e.g. after 6:00 pm. In this case, you need to compare only
the time portion with this time. .Net does not have time only datatype. You can use the following function to do comparison.
Function CompareTimePortion(ByVal dateWithLargeTimePortion As Date,
_
ByVal dateWithSmallTimePortion As Date) As Boolean
If GetTimePortionValue(dateWithLargeTimePortion) >
_
GetTimePortionValue(dateWithSmallTimePortion) Then Return True Else Return False End If End Function
Function GetTimePortionValue(ByVal d As Date) As Long Return d.Ticks - DateTime.Parse(d.ToShortDateString).Ticks End Function
How to Get a date's Last Day of Month
Function LastDayOfMonth(ByVal d As DateTime) As DateTime Return d.AddDays(DateTime.DaysInMonth(d.Year, d.Month) - d.Day) End Function
How to ensure dd-mm-yy string input of a date not intepreted as mm-dd-yy
Function String2Date(ByVal DDMMYY As String) As DateTime Return DateTime.Parse(DDMMYY, New System.Globalization.CultureInfo("en-GB")) End Function
You can also download the code from here.
OTHER POPULAR BLOGS
|