none
Date Formats in VB.NET

    Question

  •  

    Hi,

        Is there any way to make VB.NET to accept for all Date Formats as in VB6.0...

    I'm upgrading VB6.0 applications to VB.NET... Here I'm finding the Functionality difference due to VB.NET feature which goes for System date Settings.

     

               I tried using CultureInfo. But it  also specifies only one format at a time...Plz help me in removing this functionality difference

     

     

    Explanation : IsDate("MM/DD/YYYY") Returns False if the system date setting is of "DD/MM/YYYY"

     

    Regards,

     Jayaseelan

    Friday, March 07, 2008 7:20 AM

Answers

  • You are still not providing a valid  example of the point you wish to make. The example you give is  jan 01 2008.    Here are FOUR ways that Vb.Net will accept it

     

    Dim d As Date = CDate("jan 01 2008 ")

    MessageBox.Show(d.ToString())

    Dim d2 As Date = CType("jan 01 2008", Date)

    MessageBox.Show(d2.ToString())

    Dim d3 As Date = Convert.ToDateTime("jan 01 2008")

    MessageBox.Show(d3.ToString())

    Dim d4 As Date

    Date.TryParse("jan 01 2008", d4)

    MessageBox.Show(d4.ToString)

     

     

    So you are not really "showing" that Vb.net is incapable of working with all date formats. All you have shown is the obvious fact that it cannot do the logical impossibility of resolving ambiguities. For example, if the current Windows date format is MM/dd/yyyy (by virtue of the culture setting)  then obviously the following is going to throw an exception:

     

    Dim d as Date = CDate("22/05/2008")

     

    The fact that .Net is smart enough to throw an exception here doesn't construe it as "incapable of working with all the date formats."

    Saturday, March 08, 2008 2:20 PM

All replies

  • To convert string into date, use TryParse:

        http://msdn2.microsoft.com/en-us/library/system.datetime.tryparse.aspx

     

    If you want to convert with a specific format use ParseExact:

        http://msdn2.microsoft.com/en-us/library/system.datetime.parseexact.aspx

    Friday, March 07, 2008 1:29 PM
  • I don't know VB6, but I fail to see how it could know whether a date such as

    01 02 2007  means "Feb 1" or "Jan 2" - this is an ambiguity in ANY programming language it seems to me.

     

    Here is what I have in my notes - although I haven't done any testing on it.

     

    Validating Dates

     

    A fast way to validate a date is to use Date.TryParseExact because it doesen't throw any exceptions, so it's very fast. Instead, an invalid date will return the System.DateTime.MinDate value which is way back in the year one A.D. YOu pass in a date by reference and along with a custom date formatting code to indicate what date format you are using.

     

    Dim d As Date 'This variable is passed in by reference.

    Date.TryParseExact("22/05/1900", New String() {"dd/MM/yyyy"}, Nothing, Globalization.DateTimeStyles.AdjustToUniversal, d) 'no exception throws

    MessageBox.Show(d.ToString) 'Outputs May 22 1900

    Date.TryParseExact("05/22/1900", New String() {"MM/dd/yyyy"}, Nothing, Globalization.DateTimeStyles.AdjustToUniversal, d) 'no exception throws

    MessageBox.Show(d.ToString) 'Outputs May 22 1900

     

    Some of the custom formatting codes are case sensitive (MM is not the same as mm). All of this is documented on MSDN . The custom codes are as follows:

     

    MMMM Month as a whole word such as June

    dddd The day as a whole word such as Saturday

    yyyy The year as 4 digits such as 1999

    yy - 2 digit year

    dd The day as two digits such as 05 - a leading zero is added for single digit date.

    d - The day as 1 digit (unless that day has two digits). No leading zero added for sngle digit date.

    MM The month as two digits such as 12 - leading zero added for single digit.

    M - Month as a single digit (unless that month has 2 digits), no leading zeroes added for single digit.

    MMM - month as word but abbreviated.

    ddd - Name of the day abbreviated such as "Sat". (Culture specific).

    hh - Two digit hour in 12 hour time (non-military time), adds a leading zero if necesssary.

    h - 1 digit hour in non-military time (unless that hour has two digits).

    HH - 2 digit hour in military time 00 to 23(adds a leading zero if necessary).

    H - 1 digit hour in military time 0 to 23 (no leading zero added).

    mm - two digit minute,

    m - 1 digit minute (unless that minutes has 2 digits).

    gg - Adds A.D. or B.C. to the date

    tt Am or Pm , culture specific.

    Friday, March 07, 2008 10:44 PM
  • Hi,

             What u have given is right..It's working fine......But If I want to convert any date formats to MM/dd/YYYY what I need to do......

     The code that you have given works only for one date format.

     

      Plz refer and guide me...........

    Saturday, March 08, 2008 5:24 AM
  • I don't think you can change the way that a date is stored internally, because, like you said, Windows stores the date in a specific format based on the current culture.

     

    I think you are faced with a two step process. The first step is to come up with a TryParseExact formula (using the codes I gave you) for each type of date string in your data, as to create a date object stored according to the current Windows culture.  For cases where you can’t seem to come up with a TryParseExact formula, you will have to manually parse the string (using MyString.Substring) to create the date format needed.

     

     

    Now for Step 2. Now that you have the date stored in the current Windows format, you need to convert it to the desired format.  Will you be dealing with multiple cultures? If so, the first question is whether you REALLY want MM/dd/yyyy (which is called ShortDateString format) for all scenarios or, what is more likely, you want the equivalent of that in any culture. Take for example the French culture:

     

    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");

            MessageBox.Show(DateTime.Now.ToShortDateString());

     

    The output for the French culture would be dd/MM/yyyy. So if you think your program will be used in France, you might want to use ShortDateString to make the dates intelligible to them.

     

    For the invariant culture (a culture intended for programming purposes only rather than for users to actually see) the ShortDateString is in fact the one you wanted (MM/dd/yyy)

     

    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(""); //invariant culture

     

     

    So I suppose one solution is to use the above line of code to put the invariant culture in place.

     

    If you don’t want to mess with culture, another solution is to use formatting codes. Microsoft provides two different kinds, Standard and Custom.  (“Custom” doesn’t mean self-invented. It merely means that the codes refer to the component parts such as dd or MM and you get to arrange the components in any combination). Each Standard code is a preestablished combination that you can’t change – less flexible.

     

    You  might not want to use Standard codes since they are culture specific. In other words if you use the standard code “d” which happens to mean ShortDateString, the output would not be the desired MM/dd/yyyy if the current culture is French (as shown above).  Of course this code will work fine if you are fairly certain that only computers set to US culture will be using your program.

     

    But to transcend culture entirely (i.e. culture independent), you can use the Custom codes (the ones I gave you above) to convert a date to the desired MM/dd/yyyy.

     

    Here are some sample conversions:

     

            Dim date1 As Date = DateTime.Now

            Dim str As String = date1.ToString("yyyy/MM/dd")

            MessageBox.Show(str)

            'The alternative syntax is this - does the same thing but comes in handy in cases where .Net does not allow the ToString method

            str = String.Format(" Here is the date:    {0:yyyy/MM/dd}     that I wanted you to see.", date1)

            MessageBox.Show(str)

            Dim date2 As Date = DateTime.Now.AddYears(500)

            'the  0  is an index. For the first date use 0, the second date use 1.

            str = String.Format(" Here are two dates. First is:    {0:yyyy/MM/dd}     and second is  {1:yyyy/MM/dd}.", date1, date2)

            MessageBox.Show(str)

     

     

    The above are examples of Custom Codes. If you decide to use Standard Codes, here’s the list (keep in mind that the output will vary from culture to culture, unlike with Custom coding).

     

                                                    Standard Date Codes

     

    d          ShortDateString    Culture-specific. For invariant culture it is "MM/dd/yyyy".        

    D         LongDateString.  Culture-specific. For invariant culture it is  "dddd, dd MMMM yyyy".   

    f           LongDateString + ShortTimeString  - Culture specific. Combines "D" and "t", separated by a space.        

    F          LongDateString + LongTimeString. Culture specific. For invariant culture it is "dddd, dd MMMM yyyy HH:mmTongue Tieds".              

    g          ShortDateString +  ShortTimeString. Culture specific. Combines d and t.

    G         ShortDateString + LongTimeString. Culture specific. Combines d and T.

    M or m MonthDayString such as June 12. Culture specific.

    Y or y YearMonthString such as  September, 2007.

    t           ShortTimeString

    T          LongtimeString

    o          Round-trip date/time pattern     Represents a custom DateTime format string using a pattern that preserves time zone information. The pattern is designed to round-trip DateTime formats, including the Kind property, in text. Then the formatted string can be parsed back using Parse or ParseExact with the correct Kind property value.          

     

     

     

     

    Saturday, March 08, 2008 9:50 AM
  • Thanks jal.......So tell me is my conclusion right..........It is not possible to make VB.NET to accept for all date formats. i.e it does not provide direct commands for it....

                If we wish we can do it using Culture Info...That too after analysing which format of the date is entered and accordingly we need to set the current culture........

     

             OK jal if my conclusions are right I try to do it by CultureInfo as you have said........

    Saturday, March 08, 2008 11:21 AM
  • I'm just a beginner, too, so I'm probably not understanding your question. To me the notion of "accepting all date formats" doesn't really make sense because some of them are ambiguous, as I said. Again, the date  01/02/1955 could either refer to january or to february. So I think you're asking a logical impossibility in ANY programming language, as I said before.

     

    But yes, there is in .Net a command that can "try" to  convert any string to a date, namely

     

    Dim d as Date = Convert.ToDateTime(stringDate1)

     

    There are two problems with this method, (1) It doesn't resolve the kinds of ambiguities I mentioend above - it can't do so but such an expectation would be unreasonable (i.e. a logical impossibility).

    (2) This method is a bit slow for invalid dates because it throws an exception.

     

     

    Saturday, March 08, 2008 11:42 AM
  • I forgot to mention that in addition to Convert.ToDateTime there is also

     

     

    Dim d As Date = CDate("1/1/2000")

    Dim d2 As Date = CType("1/1/2000", Date)

     

     

    But I don't know the differences in all these methods.

    Saturday, March 08, 2008 11:46 AM
  • Hi,

             As I said earlier in VB all the date formats will be accepted. and The Prefernce is given to "MM/DD/YYYY"(May be System date)....... If Suppose I enter the date as jan 01 2008 It will take this as valid date......Whereas VB.NET do not....

     

    That's why I'm asking is there any way to accept  all date formats

     

    Saturday, March 08, 2008 11:53 AM
  • You are still not providing a valid  example of the point you wish to make. The example you give is  jan 01 2008.    Here are FOUR ways that Vb.Net will accept it

     

    Dim d As Date = CDate("jan 01 2008 ")

    MessageBox.Show(d.ToString())

    Dim d2 As Date = CType("jan 01 2008", Date)

    MessageBox.Show(d2.ToString())

    Dim d3 As Date = Convert.ToDateTime("jan 01 2008")

    MessageBox.Show(d3.ToString())

    Dim d4 As Date

    Date.TryParse("jan 01 2008", d4)

    MessageBox.Show(d4.ToString)

     

     

    So you are not really "showing" that Vb.net is incapable of working with all date formats. All you have shown is the obvious fact that it cannot do the logical impossibility of resolving ambiguities. For example, if the current Windows date format is MM/dd/yyyy (by virtue of the culture setting)  then obviously the following is going to throw an exception:

     

    Dim d as Date = CDate("22/05/2008")

     

    The fact that .Net is smart enough to throw an exception here doesn't construe it as "incapable of working with all the date formats."

    Saturday, March 08, 2008 2:20 PM
  • OK jal.....the last statement that you've given is the one which  I was expecting for.........So I'm continuing with your valuable comments............ Thanx......

     

    Monday, March 10, 2008 4:56 AM
  • Dear friends my sql qurey for search date is not  working, i want to search between dates using ms access database with vb.net, ado.net, oledb

    yes i set date formate short and dd/mm/yyyy both in system control panel and access database table.

     

    i m using following qurey but it is not working

    sql = "select * from table where date_col =>'" & txtDate.text & "'"

    the code i m using is

     PurchaseDa.Dispose()
            PurchaseDs.Clear()
            PurchaseDt.Clear()
            PurchaseConn.ConnectionString = "Provider=Microsoft.jet.oledb.4.0; Data Source=" & Pth & "\DisplayCenterData.mdb; User Id=admin; Password=;"

          purchasesql = "select * from purchase where purchasedate=>'" & txtDate.text & "'"

            PurchaseConn.ConnectionString = "Provider=Microsoft.jet.oledb.4.0; Data Source=" & Pth & "\DisplayCenterData.mdb; User Id=admin; Password=;"

            PurchaseDa = New OleDbDataAdapter(PurchaseSql, PurchaseConn)

            PurchaseDs = New DataSet
            PurchaseDa.Fill(PurchaseDs, "DisplayCenterData")
            PurchaseDt = PurchaseDs.Tables("DisplayCenterData")

            PurchaseCmb = New OleDbCommandBuilder(PurchaseDa)

            PurchaseDa.InsertCommand = PurchaseCmb.GetInsertCommand
            PurchaseDa.UpdateCommand = PurchaseCmb.GetUpdateCommand

         txtPurchaseID.DataBindings.Clear()
            txtCompanyID.DataBindings.Clear()
            txtBookID.DataBindings.Clear()
            txtPurchaseDate.DataBindings.Clear()

    txtPurchaseID.DataBindings.Add("text", PurchaseDt, "purchaseID")
            txtCompanyID.DataBindings.Add("text", PurchaseDt, "companyID")
            txtBookID.DataBindings.Add("text", PurchaseDt, "BookID")
            txtPurchaseDate.DataBindings.Add("text", PurchaseDt, "PUrchaseDate")

     

     

    I also Tried following quries and techniques but not working

     

            PurchaseSql = "Select * from PUrchase where PurchaseDate => '" & DatePurchaseFrm.Value.ToString("dd-MM-yyyy") & "' order By PUrchaseID"

            PurchaseSql = "Select * from PUrchase where PurchaseDate =@05/04/2010  order By PUrchaseID"

            PurchaseSql = "SELECT * FROM purchase WHERE PUrchaseDate between '" & Format(Me.DatePurchaseFrm.Value, "dd/dd/yyyy") & "' AND '" & Format(Me.DatePurchaseTo.Value, "dd/MM/yyyy") & "'"

            PurchaseSql = "Select * from PUrchase where PurchaseDate ='" & DatePurchaseFrm.Value & "' order By PUrchaseID"

            PurchaseSql = "Select * from PUrchase where CONVERT(CHAR(10),PurchaseDate) =>" & DatePurchaseFrm.Value.ToString("dd-mm-yyyy") & " order By PUrchaseID"

            PurchaseSql = "SELECT * FROM Purchase WHERE PurchaseDate>= DateValue('" & DatePurchaseFrm.Value & "')" & " ORDER BY PurchaseID"

            PurchaseSql = "select * from Purchase"
            PurchaseSql = "Select * from PUrchase where CONVERT(CHAR(10),PurchaseDate,103) BETWEEN '" & DatePurchaseFrm.Value.ToString("dd/MM/yyyy") & "' AND '" & DatePurchaseTo.Value.ToString("dd/MM/yyyy") & "' order By PUrchaseID"
            PurchaseSql = "Select * From Employees Where HireDate Between #1/1/1990# and #12/31/2010#"

      Dim dt As Date
            dt = FormatDateTime(DatePurchaseFrm.Value, DateFormat.ShortDate)
            MsgBox(dt)

            PurchaseSql = "Select * from PUrchase where PurchaseDate => '" & dt.ToString("MM-dd-yyyy") & "' order By PUrchaseID"

    Wednesday, April 21, 2010 6:11 AM