I had a problem manipulating the textbox. This is the date format 2019-10-10 05-21-27 and I was about to convert it using datetime. But it seems it cannot be Format like this 2019-10-10 05:21:27 I tried several codes for this one but it did not work.
Here is my code:
Dim d As Date = Date.ParseExact(tbox_dateofS.Text, "d/M", CultureInfo.InvariantCulture)
tbox_dateofS.Text = d.ToString("dd/MM/yy hh:mm:ss")
i tried this one also:
tbox_dateofS.Text = Cdate(node.SelectSingleNode("starttime").InnerText).Tostring("yyyy-mm/dd hh:mm:ss"
And I got this error : System.FormatException: 'String was not recognized as a valid DateTime.'
Of course it can be formatted like that. You simply need to specify the correct format to convert FROM in order to get a Date that you can then format however you want.
Imports System.Globalization
Module Module1
Sub Main()
Dim text = "2019-10-10 05-21-27"
Dim dt As Date
If Date.TryParseExact(text, "yyyy-MM-dd HH-mm-ss", Nothing, DateTimeStyles.None, dt) Then
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"))
Else
Console.WriteLine("Invalid input")
End If
Console.ReadLine()
End Sub
End Module
It works exactly as you should expect.
That said, why use a TextBox in the first place? In most cases, you can use a DateTimePicker and it will handle all the formatting and validation for you.
05-21-27 is a bad format (WITH FORMAT STYLE "d/M") to convert in a time object.
So if you don’t want to change your INPUT format use the method below as a workaround otherwise in order to have a correct date Object you need to change your time input string in 05:21:27 and after to format this date in your style again as you want.
Private Function getFormatedDate(sDate As String, Optional formatString As String = "yyyy-MM-dd HH:mm:ss")
Dim correctDateString As String = ""
For i As Integer = 0 To sDate.Length - 1
If IsNumeric(CChar(sDate(i))) OrElse sDate(i) = " " Then
correctDateString &= sDate(i)
Else
If i < 10 Then
correctDateString &= "/"
Else
correctDateString &= ":"
End If
End If
Next
Return Strings.Format(CDate(correctDateString), formatString)
End Function
Usage:
Dim mCorrectDateString As String = getFormatedDate("2019-10-10 05-21-27")
Related
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)
I'm trying to use this code:
If Not IsError(Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT"))) Then
MyString = "'" & Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT")).ToString("yyyy-MM-dd") & "'"
Else
'Do something else
End If
My goal is to assign value to "MyString" only if "Convert.ToDateTime" gives a valid value but the code doesn't do that: It stops when the String isn't recognized as a valid DateTime instead of execute the "else" code.
You should use DateTime.TryParse:
https://msdn.microsoft.com/en-us/library/9h21f14e%28v=vs.110%29.aspx
If you don't know exactly what is the format in which you receive your string then you need to provide a set of possible formats to the DateTime.TryParseExact.
This example below is a simplified test version of your code above
Sub Main
Dim dateConverted as DateTime
Dim testDate = "asdfasldka:08/05/2015 13:10"
Dim yourWannaBeDate = testDate.Substring(testDate.IndexOf(":") + 1).Trim()
Dim possibleFormats = new string() {"d/M/yyyy", "d/M/yyyy H:m", "d/M/yy", "d/M/yy H:m"}
if DateTime.TryParseExact(yourWannaBeDate, possibleFormats, CultureInfo.CurrentCulture, DateTimeStyles.None, dateConverted) then
Console.WriteLine(dateConverted.ToString("yyyy-MM-dd"))
else
Console.WriteLine("Not a date")
End if
End Sub
The above code will match "08/05/2015", "8/5/2015", "08/05/15" and the same strings with the time part in two or one digit format
The trick consists in passing an array of possible formats that could be used to interpret the date in your CurrentCulture (I am assuming that your PC has the culture that match the formats above, however, if this is not the case just initialize a new CultureInfo variable and use it in the TryParseExact)
I wanna thank Leonardo for the tip. This is the code I successfully used:
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("it-IT")
Dim DateResult As DateTime
Dim styles As DateTimeStyles = DateTimeStyles.None
Dim mTmpDate As String
mTmpDate = DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim()
If DateTime.TryParse(mTmpDate, culture, styles, DateResult) Then
MyString = "'" & DateResult.ToString("yyyy-MM-dd HH:mm") & "'"
Else
'Do something else
End If
The code works with any kind of date in "italian style" and in "MyString" I get a date/time formatted as mySql needs (for a timestamp field).
When I am doing in immediate window
? IsDate("09/01/14")
True
? IsDate("10/23/14")
False
I am not sure why IsDate("10/23/14") is returning false.
any suggestions?
This is my entire function. When I pass 09/01/14 then it doesn't return any error, but when I pass 10/23/14 then it returns error.
Public Shared Sub CheckForDate(ByVal ChkText As String, ByRef ErrorCount As Integer)
Try
ChkText = ChkText.Replace(" ", "").Trim()
Dim dt As DateTime = DateTime.ParseExact(ChkText, "MM/dd/yyyy", Globalization.CultureInfo.InvariantCulture)
If Not IsDate(dt) Then
ErrorCount += 1
End If
Catch
If Len(ChkText) > 0 Then
If Not IsDate(ChkText) Then
ErrorCount += 1
End If
End If
End Try
End Sub
I tried this
? DateTime.TryParse("09/01/14", dt)
True
? DateTime.TryParse("10/23/14", dt)
False
It might be possible that dates in isDate are being processed as dd/mm/yy instead of mm/dd/yy.
Try this code in your application, or be sure your system is processing dates as mm/dd/yy:
Imports System.Globalization
Dim ciNewFormat As New CultureInfo(CultureInfo.CurrentCulture.ToString())
ciNewFormat.DateTimeFormat.ShortDatePattern = "MM/dd/yy"
System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat
Use TryParseExact(). This will force you include information indicating the expected format.
As somewhat indicated in comments on this question, the likely problem is that the machine where you are running assumes a DD/MM/YY format instead of your expected MM/DD/YY format.
You must specify a culture that corresponds to date format used:
Public Shared Function IsUSDate(input As String) As Boolean
Dim culture = CultureInfo.CreateSpecificCulture("en-US")
Dim d As DateTime
Return DateTime.TryParse(input, culture, DateTimeStyles.None, d)
End Function
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
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