Validate the date format in vb.net - vb.net

I have the grid cell value to validate for a correct format as below
Date value should be in DD-MON-YYYY format and for this i am using below validation
Public Function ValidateDateForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As DateTime
If Date.TryParseExact(checkInputValue, "DD-MON-YYYY",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
Else
MessageBox.Show("not converted")
End If
Return returnError
End Function`
DateTime value should be in DD-MON-YYYY HH:MI:SS format and for this i am using below validation
Public Function ValidateDateTimeForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As DateTime
If DateTime.TryParseExact(checkInputValue, "DD-MON-YYYY HH:MI:SS",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
End If
Return returnError
End Function`
EDate (valid European date) value should be in DD/MM/YY format and for this i am using below validation
Public Function ValidateEDateForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As Date
If Date.TryParseExact(checkInputValue, "DD/MM/YY",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
End If
Return returnError
End Function`
JDate (valid Julian date) value should be in MM/DD/YY format and for this i am using below validation
Public Function ValidateJDateForError(ByVal checkInputValue As String) As Boolean
Dim returnError As Boolean
Dim dateVal As Date
If Date.TryParseExact(checkInputValue, "MM/DD/YY",
System.Globalization.CultureInfo.CurrentCulture,
DateTimeStyles.None, dateVal) Then
returnError = True
End If
Return returnError
End Function`
but none of above is working. could anyone tell me where i am making mistake?
Thanks in Advance.

Using ParseExact means that you will be telling it the precise format the string will be in. These are case sensitive to allow things like H vs h for 12/24 clock and MM vs mm to distinguish Month from Minutes. So, "DD-MON-YYYY" is invalid, "dd-MM-yyyy" may be what you are after.
But, this means the user would always have to enter 2 digits for the day and month as in "19-07-2014" or "04-07-2014" which they are often not inclined to do, and seems harsh to impose. TryParseExact will take an array of formats so you can be flexible:
Dim strFoo As String = "19-7-2014" ' d-MM-yyyy
Dim strBar As String = "19-07-2014" ' dd-MM-yyyy
Dim strJuly4 As String = "4-7-2014" ' d-M-yyyy
' several possible format styles
Dim formats() As String = {"d-MM-yyyy", "dd-MM-yyyy",
"dd-M-yyyy", "d-M-yyyy"}
Dim thisDt As DateTime
' this should work with all 3 strings above
If DateTime.TryParseExact(strFoo, formats,
Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None, thisDt) Then
Console.WriteLine("Success! {0}", thisDt.ToString)
End If
Most of the time there it is silly to force them to enter "04" for a month or day and d/M/yyyy will work with strings with the leading "0" (but not the reverse!). Its is added here mainly to show how to pass an array of format patterns.
DO consult MSDN for the proper Standard Date and Time Format Strings
As for Julian Dates, one form of them is to use the form yyDDD to denote the 2 digit year and day of year for the last 3 digits. I dont know if the convention for this changed after 1/1/2000 when all Julian for this Century would sort below those for the 1990s. Still, here is how it is done:
Dim jdt As DateTime = #2/11/2010#
Dim jdate As String = xdt.Year.ToString & xdt.DayOfYear.ToString("000")
' ===> '2010042 or 42nd day of 2010
jdate = (xdt.Year - 2000).ToString("00") & xdt.DayOfYear.ToString("000")
' ===> '10042 or 42nd day of 2010

Related

Manage different date formats in vb.net

I'm trying to figure out how best to handle different date formats that I might have as input.
The specific case is about the dates dd/MM/yyyy and MM/dd/yyyy.
At the time I try to convert the date as below:
firstDate = CDate("10/22/1988")
It obviously returns an error, how can I handle both cases in a generic way?
You can use Date.TryParseExact with the allowed format patterns:
Dim patterns As String() = {"dd/MM/yyyy", "MM/dd/yyyy"}
Dim dt As Date
Dim valid = Date.TryParseExact(str, patterns, CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
Here a full working demo:
Sub Main
Dim inputs As String() = {"10/22/1988", "22/10/1988"}
Dim patterns As String() = {"dd/MM/yyyy", "MM/dd/yyyy"}
For Each str As String In inputs
Dim dt As Date
Dim valid = Date.TryParseExact(str, patterns, CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
Console.WriteLine($"Valid: {valid} Date-Value: {dt}")
Next
End Sub
Output(i'm in germany):
Valid: True Date-Value: 22.10.1988 00:00:00
Valid: True Date-Value: 22.10.1988 00:00:00
In case of input like "3/5/1988" you should also allow:
"M/d/yyyy", "d/M/yyyy"
In this case the order is also the priority, so if both could work, the first wins.

How to get substring date (year) using vb.net?

I've been doing this, is it possible to get the middle string in datetime.
Example :
Basically my string return this '12/23/2015 12:00:00 AM'.
However, what i want is actually '15' from the year 2015.
I've been using something like this 'strDate = strDate.Substring(0, 9)',
which sometimes return me wrong when the date is something like this '1/2/2015 12:00:00 AM'
Can someone help me on this, i am not sure if we can get the middle.
Don't use string methods for this, use DateTime.TryParseExact:
Dim str = "12/23/2015 12:00:00 AM"
Dim dt As DateTime
If DateTime.TryParseExact(str, "MM'/'dd'/'yyyy hh:mm:ss tt", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dt) Then
Dim yearOnly As String = dt.ToString("yy") ' 15
End If
Update: with CultureInfo.InvariantCulture and this format you don't even need to use TryParseExact, you can use Parse/TryParse immediately:
DateTime.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
MSDN: Custom Date and Time Format Strings, The "yy" Custom Format Specifier
If you really want to treat it as just strings, you can get it by splitting twice. First on the space, then on the slashes:
Dim justDate as String = strDate.Split(" ")(0) 'contains "12/23/2015"
Dim justYear as String = justDate.Split("/")(2) 'contains "2015"
Dim partYear as String = justYear.Substring(2,2) 'contains "15"
or all in one line:
Dim partYear as String = strDate.Split(" ")(0).Split("/")(2).Substring(2,2)
Try this
dim dateStr as string
dateStr = "12/23/2015 12:00:00 AM"
dim dateobj as new DateTime
dateobj = DateTime.Parse(dateStr)
dim year as integer
year = dateobj.Year
dim youWantStr = year.ToString().Substring(2)
Console.WriteLine(youWantStr)

How CDATE perform its conversion from string to date on VB.NET

I just want to ask how VB.NET perform is conversion of date from string. I am currently designing a database view and convert the date into MMddyyyy format, but I am worried that CDATE it will read it as ddMMyyyy.
I want it to make it shorter and converting the date using CDATE instead of using the traditional M/d/yyyy h:mm:ss tt.
Example:
Dim myDate As Date = CDate(DataTable.Rows(0).Item("DateValue").ToString())
CDate depends on the control panel regional settings and is not recommended - you should use Date.ParseExact instead
Const MyDateFormat As String = "MMddyyyy"
Dim dte As Date = #2/1/2003#
'convert the date to a string
Dim strDate As String = dte.ToString(MyDateFormat)
'convert the string back to a date
Dim dte2 As Date = Date.ParseExact(strDate, MyDateFormat, System.Globalization.CultureInfo.InvariantCulture)
If dte = dte2 Then
MsgBox("They're the same :-) " & strDate)
Else
MsgBox("They're different :-(")
End If
For your code, it would look like:
Dim myDate As Date = Date.ParseExact(DataTable.Rows(0).Item("DateValue").ToString(), "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture)

isDate control on european data in vb.net

How can i do a isDate() control on a date like 16/01/2008 in vb.net?
To check if 16/01/2008 is a valid date, you do:
Dim result As Date
If Date.TryParse("16/01/2008", result) Then
'The date is valid '
End If
Now this will use the current culture set. If you want to validate it against a specific culture, you can do it like this (example with french culture):
If Date.TryParse("16/01/2008", Globalization.CultureInfo.GetCultureInfo("fr-FR"), _
Globalization.DateTimeStyles.None, result) Then
'The date is valid '
End If
If the date format in your input data is fixed to month/day/year and does not depend on the current culture, you should use DateTime.TryParseExact:
Public Shared Function IsValidInputDate(ByVal str As String) As Boolean
Dim dt as DateTime
Return DateTime.TryParseExact(str, "d/M/yyyy", Nothing, Globalization.DateTimeStyles.None, dt)
End Function

How can I convert two strings to DateTimes and compare them in VB.NET?

String comes back from the database with a format: '00/00/0000' I need to then compare it to a date that the user has entered in the same format. How do I make the conversion and compare the two dates?
Use the static ParseExact method on the DateTime structure to convert the string. You will also pass the format you want, either dd/MM/yyyy or MM/dd/yyyy depending on what format you want (the example of 00/00/0000 doesn't give any indication of what format applies for you).
You can use
Dim dateA = DateTime.ParseExact(firstDateString, #"dd\/MM\/yyyy", Null)
Dim dateB = DateTime.ParseExact(secondDateString, #"dd\/MM\/yyyy", Null)
Dim areEqual = (dateA = dateB);
Assuming that your date format is day/month/year.
If it's month/day/year just swap dd and MM
Try something like this:
String.Compare("00/00/0000", dateTime.ToString("MM/dd/yyyy"))
But perhaps a better approach would be to do this:
DateTime.Equals(yourDateTime, DateTime.Parse(databaseDateTime));
Try the following
Dim date1 = CDate(firstDateString)
Dim date2 = CDate(secondDateString)
Dim comp = date1 = date2
When you say compare, are you trying to analysis if the dates are the same (to the day) or within a period of a few days ? If to compare if the dates are the same then you can just compare the string or use the date.equals (as mentioned in posts before this one) , if you are trying to determine with a range you will have to use date compare
Dim lDate1 As String = "29/03/2009"
Dim lDate2 As String = "30/03/2009"
Dim lPeriod As Int16 = 7
If lDate1 = lDate2 Then
'** Dates the same
End If
If Date.Equals(Date.ParseExact(lDate1, "dd/MM/yyyy", Nothing), Date.ParseExact(lDate2, "dd/MM/yyyy", Nothing)) Then
'** The same
End If
If Date.Compare(Date.ParseExact(lDate1, "dd/MM/yyyy", Nothing), Date.ParseExact(lDate2, "dd/MM/yyyy", Nothing)) > (lPeriod * -1) And Date.Compare(Date.ParseExact(lDate1, "dd/MM/yyyy", Nothing), Date.ParseExact(lDate2, "dd/MM/yyyy", Nothing)) < lPeriod Then
'** Within the period
End If