locked
Converting Raw Text to date RRS feed

  • Question

  • I am working with some raw data, I have a label which has a text "10/02/2010" I want this text to be converted to a date in this format dd/mm/yyyy

    How can i do this in vb.net

    Any help will be appreciated

    Thanks


    • Edited by Sid Williams Saturday, September 22, 2012 7:10 PM
    Saturday, September 22, 2012 7:10 PM

Answers

  • Hi Sid,

    go to : Converting a string into required date format in vb.net


    Pl. Mark/Proposed as Answer if found your solution Vote as Helpful if related to your topic. Always Motivate others by performing this Action.

    • Proposed as answer by Leo Zuo Monday, September 24, 2012 5:37 AM
    • Marked as answer by Youen Zen Tuesday, October 2, 2012 6:59 AM
    Saturday, September 22, 2012 7:15 PM
  • What I don't like about the  DateTime.ParseExact method is that it does what it's meant to do: You tell it in advance what culture it's supposed to be.

    That's further restricting what the user can enter (assuming they're typing it in - in which case, why not use a DateTimePicker control) and, moreover, unlike DateTime.TryParse, it blows up if fails. From the MSDN page referenced:

    "The format of the string representation must match the specified format exactly."

    Are you going to include a way for the user to select which culture it's supposed to be in?


    Please call me Frank :)

    • Marked as answer by Youen Zen Tuesday, October 2, 2012 7:00 AM
    Saturday, September 22, 2012 8:42 PM
  • This works too

    Imports System
    Imports System.IO
    Imports System.Text
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
    
        End Sub
    
        Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Date1 As String = Label1.Text
            Dim Date1Array(Date1.Length) As Char
    
            Using Date1StringReader As StringReader = New StringReader(Date1)
                Date1StringReader.Read(Date1Array, 0, 10) '10 characters in Date1Array
            End Using
    
            Dim Date1StringBuilder As New StringBuilder("")
            Using Date1StringWriter As StringWriter = New StringWriter(Date1StringBuilder)
                ' Write ten characters from the array into the StringBuilder.
                Date1StringWriter.Write(Date1Array, 3, 1)
                Date1StringWriter.Write(Date1Array, 4, 1)
                Date1StringWriter.Write(Date1Array, 5, 1)
                Date1StringWriter.Write(Date1Array, 0, 1)
                Date1StringWriter.Write(Date1Array, 1, 1)
                Date1StringWriter.Write(Date1Array, 2, 1)
                Date1StringWriter.Write(Date1Array, 6, 1)
                Date1StringWriter.Write(Date1Array, 7, 1)
                Date1StringWriter.Write(Date1Array, 8, 1)
                Date1StringWriter.Write(Date1Array, 9, 1)
    
                Label2.Text = Date1StringBuilder.ToString
    
            End Using
    
        End Sub
    
    End Class


    You've taught me everything I know but not everything you know.


    • Edited by Mr. Monkeyboy Sunday, September 23, 2012 1:24 AM
    • Marked as answer by Youen Zen Tuesday, October 2, 2012 7:00 AM
    Sunday, September 23, 2012 1:20 AM
  • Sid,

    If somebody else wrote this, than sorry. 

    However, a date is not a string, it is a struct with many methods to convert a date but only one data item which is an Int64 with the name Tick 

    You cannot set it by an = because it is read only and therefore only construct with phrases like

    dim x = new DateTime(2012,9,23)

    Because it by using one of it endless methods (very important the overloaded ToString) you can show it in every string format you want, you don't convert a date. For converting a string representation like yours you can use the convert. 

    Your sample can simple be done with a Convert to Date (Cdate) 

    dim theDateIWantToUse = CDate("10/02/2010")

    With this date format the program assumes it is has the format like it is the most used in the world. DD MM YYYY

    (The DateTime Tick is an Int64 which contains 100th nanoseconds ticks starting at 1-1-1 using the Gregorian Calendar)


    Success
    Cor



    • Edited by Cor Ligthert Sunday, September 23, 2012 5:39 AM
    • Marked as answer by Youen Zen Tuesday, October 2, 2012 7:00 AM
    Sunday, September 23, 2012 5:35 AM

All replies

  • Hi Sid,

    go to : Converting a string into required date format in vb.net


    Pl. Mark/Proposed as Answer if found your solution Vote as Helpful if related to your topic. Always Motivate others by performing this Action.

    • Proposed as answer by Leo Zuo Monday, September 24, 2012 5:37 AM
    • Marked as answer by Youen Zen Tuesday, October 2, 2012 6:59 AM
    Saturday, September 22, 2012 7:15 PM
  • Dim s As String = "10/02/2010"
    Dim d As DateTime = DateTime.Parse(s, New Globalization.CultureInfo("en-GB"))

    Note that a DateTime does not have a format - that is only materialized in a string if you convert the DateTime to a string.

    --
    Andrew


    Saturday, September 22, 2012 7:39 PM
  • If you have a fixed format, you can use PaseExact method, where you define the exact date format, so there cannot be any ambiguities:

    Dim strDate As String = "10/02/2010"
    Dim [date] As DateTime = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)


    Mitja

    Saturday, September 22, 2012 7:39 PM
  • Les,

    I do see both lines of the code in my earlier reply, and I see both lines, with a horizontal scrollbar, in Mitja's reply. Checked using Firefox and IE9 on Windows 7 x64.

    Are you seeing the first or last line of my code?

    Dim s As String = "10/02/2010"

    Dim d As DateTime = DateTime.Parse(s, New Globalization.CultureInfo("en-GB"))

    Sid: apologies for this being off-thread, but this forum has been having some issues.

    --
    Andrew

    Saturday, September 22, 2012 8:08 PM
  • Les,

    You may want to post in the Forums Issues forum instead.

    --
    Andrew

    Saturday, September 22, 2012 8:37 PM
  • What I don't like about the  DateTime.ParseExact method is that it does what it's meant to do: You tell it in advance what culture it's supposed to be.

    That's further restricting what the user can enter (assuming they're typing it in - in which case, why not use a DateTimePicker control) and, moreover, unlike DateTime.TryParse, it blows up if fails. From the MSDN page referenced:

    "The format of the string representation must match the specified format exactly."

    Are you going to include a way for the user to select which culture it's supposed to be in?


    Please call me Frank :)

    • Marked as answer by Youen Zen Tuesday, October 2, 2012 7:00 AM
    Saturday, September 22, 2012 8:42 PM
  • What I don't like about the DateTime.ParseExact method is that it does what it's meant to do: You tell it in advance what culture it's supposed to be.

    But without knowing the culture, there is no hope of knowing what date 1/12/2012, for example, represents.

    Are you going to include a way for the user to select which culture it's supposed to be in?

    That isn't exactly difficult, but it appears to be beyond the scope of the original question.

    --
    Andrew

    Saturday, September 22, 2012 9:29 PM
  • This is the same as your other question.

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/52efaa4a-4d51-42cb-b448-24f4a6ba998b

    The answer is the same - you need to look at how the string got into the label.   That will tell you the source of the data that you need to use as a date, and that will tell you the sort of coversion (if any) that you need to do.

    Saturday, September 22, 2012 9:56 PM
  • This is the same as your other question.

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/52efaa4a-4d51-42cb-b448-24f4a6ba998b

    The answer is the same - you need to look at how the string got into the label.   That will tell you the source of the data that you need to use as a date, and that will tell you the sort of coversion (if any) that you need to do.

    While I don't disagree per se, as stated it doesn't matter.

    The post title is simply "Converting Raw Text To Date" so given that ... does it really matter the source? Maybe it's an XML file from a SOAP API or who knows what.

    Like I said, I'm not disagreeing per se (and he did say he has it in a label so it had come from somewhere), but there certainly are instances where you don't really know what the source is from. The example of the XML returned from an API call - if you don't know what basis the DateTime is, then ... what?

    :)


    Please call me Frank :)

    Saturday, September 22, 2012 10:41 PM
  • Addendum

    For example, have a look at this which is the return data (xml) from Last.fm for a particular music album:

    http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=Cher&album=Believe

    Look for "releasedate" not too far from the top. What format is that in? Aside from looking at it and pretty well "just knowing" what it's in, how would you know? What there states the culture?

    Let's just see what happens if I try to convert it (do keep in mind that I'm in the U.S.):

    Dim testDateString As String = "5 Jul 2005, 00:00" Dim testDate As DateTime ' If DateTime.TryParse(testDateString, testDate) Then MessageBox.Show(testDate.ToLongDateString) End If


    Amazing ... how did it know that! That's not the format that the text string was in but ...

    Anyway, enough of that - my point in that other thread and in this one is that while you can do all sorts of things like including a specific culture or any of that, "as stated for how do you convert...", in my opinion there are some things which you have to rely on.

    If it fails the test (TryParse), then investigate why but "as stated", I really don't see it as being as big a deal as others here perceive it to be.

    Just my opinion, obviously. :)


    Please call me Frank :)

    Saturday, September 22, 2012 11:02 PM
  • Amazing ... how did it know that! That's not the format that the text string was in...

    The characters "Jul" are a bit of a give-away. The parsing succeeds if you use either en-US or en-GB for that one. And you chose the output string format by using .ToLongDateString, which uses the current locale of the thread. No magic involved ;)

    --
    Andrew

    Saturday, September 22, 2012 11:36 PM
  • While I don't disagree per se, as stated it doesn't matter.

    That's certainly true, if you don't care whether or not the result is correct, or that it might create a runtime error when presented with an 'invalid' date.

    OP hasn't stated that they are concerned about these things, but I think it's reasonable to assume they would be.  That's why OP has to go back to the source for this text string, and use that to determine if (a) no conversion is required because the original data was a date or (b) conversion from a particular format is possible or (c) it cannot be determined what conversion format should be used until many more examples are provided.

    We still don't know whether the example provided was a date in February or a date in October.
    • Edited by Acamar Sunday, September 23, 2012 12:05 AM sp
    Saturday, September 22, 2012 11:48 PM
  • The characters "Jul" are a bit of a give-away. The parsing succeeds if you use either en-US or en-GB for that one. And you chose the output string format by using .ToLongDateString, which uses the current locale of the thread. No magic involved ;)

    --
    Andrew

    Right! Which was my entire point!

    As stated - how to convert text to a date - who knows what format it's in? AS STATED ... you have to rely on something or we go the full route and have a setup routine like I said earlier about setting the culture and all that.

    :)


    Please call me Frank :)

    Saturday, September 22, 2012 11:49 PM
  • Ok Acamar ... I think you're still missing my point, but that's fine too. :)

    Please call me Frank :)

    Saturday, September 22, 2012 11:55 PM
  • This works too

    Imports System
    Imports System.IO
    Imports System.Text
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
    
        End Sub
    
        Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Date1 As String = Label1.Text
            Dim Date1Array(Date1.Length) As Char
    
            Using Date1StringReader As StringReader = New StringReader(Date1)
                Date1StringReader.Read(Date1Array, 0, 10) '10 characters in Date1Array
            End Using
    
            Dim Date1StringBuilder As New StringBuilder("")
            Using Date1StringWriter As StringWriter = New StringWriter(Date1StringBuilder)
                ' Write ten characters from the array into the StringBuilder.
                Date1StringWriter.Write(Date1Array, 3, 1)
                Date1StringWriter.Write(Date1Array, 4, 1)
                Date1StringWriter.Write(Date1Array, 5, 1)
                Date1StringWriter.Write(Date1Array, 0, 1)
                Date1StringWriter.Write(Date1Array, 1, 1)
                Date1StringWriter.Write(Date1Array, 2, 1)
                Date1StringWriter.Write(Date1Array, 6, 1)
                Date1StringWriter.Write(Date1Array, 7, 1)
                Date1StringWriter.Write(Date1Array, 8, 1)
                Date1StringWriter.Write(Date1Array, 9, 1)
    
                Label2.Text = Date1StringBuilder.ToString
    
            End Using
    
        End Sub
    
    End Class


    You've taught me everything I know but not everything you know.


    • Edited by Mr. Monkeyboy Sunday, September 23, 2012 1:24 AM
    • Marked as answer by Youen Zen Tuesday, October 2, 2012 7:00 AM
    Sunday, September 23, 2012 1:20 AM
  • This works too

    No it doesn't.  OP's requirement was "...to be converted to a date".  Nowhere does your code convert anything to a date - you are simply manipulating some strings.

    Sunday, September 23, 2012 1:47 AM
  • I'm not sure what the difference is, it represents the date as 02/10/2012

    You've taught me everything I know but not everything you know.

    Sunday, September 23, 2012 1:55 AM
  • Sid,

    If somebody else wrote this, than sorry. 

    However, a date is not a string, it is a struct with many methods to convert a date but only one data item which is an Int64 with the name Tick 

    You cannot set it by an = because it is read only and therefore only construct with phrases like

    dim x = new DateTime(2012,9,23)

    Because it by using one of it endless methods (very important the overloaded ToString) you can show it in every string format you want, you don't convert a date. For converting a string representation like yours you can use the convert. 

    Your sample can simple be done with a Convert to Date (Cdate) 

    dim theDateIWantToUse = CDate("10/02/2010")

    With this date format the program assumes it is has the format like it is the most used in the world. DD MM YYYY

    (The DateTime Tick is an Int64 which contains 100th nanoseconds ticks starting at 1-1-1 using the Gregorian Calendar)


    Success
    Cor



    • Edited by Cor Ligthert Sunday, September 23, 2012 5:39 AM
    • Marked as answer by Youen Zen Tuesday, October 2, 2012 7:00 AM
    Sunday, September 23, 2012 5:35 AM
  • lol what a debate out of nothing - almost. If nothing else, its funny to read.

    In any case, we have tot much to agree around this thread`s topic, 

    Or using Parse, Convert, TryParse, ParseExact or even maybe TryParseExact methods. 

    OP just have to try them out all, and see which one suits most to his needs and whishes.

    If you ask me, I would still go for ParseExact, IF ONLY the format (Im talking about input formats - in string) is not changing. Else, if there are maybe more possible formats (inputs), then I would go for TryParseExact, and specify all possible formats in the array!


    Mitja

    Sunday, September 23, 2012 6:00 AM
  • It is quite good reading. :)

    You've taught me everything I know but not everything you know.

    Sunday, September 23, 2012 6:20 AM
  • lol what a debate out of nothing - almost. If nothing else, its funny to read.

    Mitja

    Mitja, 

    You've added this reply to my reply, therefore, is this meant as abuse?


    Success
    Cor

    Sunday, September 23, 2012 6:45 AM
  • A date is a date, a string is a string. They are different things used for different purposes.

    With a date you can do things like finding durations between dates, adding or subtracting time periods, finding the day of the week or the day of the year, converting day or month numbers to names, and so on. It can even be converted to a string (with appropriate consideration for the culture).

    A string is an array of Char. It can be reversed, dissected, reassembled and concatenated. It can even be converted to a date (sometimes).

    • Edited by Acamar Sunday, September 23, 2012 8:05 AM sp
    Sunday, September 23, 2012 8:05 AM
  • You've added this reply to my reply, therefore, is this meant as abuse?


    No Cor,

    it just came this way that my post is under yours. Never though of something like that. Its just nice to see and read what kind of "inovations" people can make almost out of nothing. Thats all I wanted to say.

    I hope you didnt take any offence. I admire your work, so I would never dare to do something like it.

    One more thing: if I want to include someone`s word in my post, I Always quote it.


    Mitja

    Sunday, September 23, 2012 11:42 AM
  • it seems you want to modify label text & fetch after correction to the same,

    Dim cusDt As Date = Date.ParseExact(lblTodaysDate.Text, _
                                                "dd/MM/yyyy", _
    System.Globalization.DateTimeFormatInfo.InvariantInfo)
            
    lblTodaysDate.Text = Format$(cusDt, "dd") & _
            "/" & Format$(cusDt, "MM") & "/" & Format$(cusDt, "yyyy")

    Same of your thread :

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/4ea89eb2-bd2b-4fb7-9166-cd3198536110

    thanks.


    Pl. Mark/Proposed as Answer if found your solution Vote as Helpful if related to your topic. Always Motivate others by performing this Action.

    Sunday, September 23, 2012 11:48 AM
  • Form with a button and a multiline textbox - Imports System.Globalization at the very top

        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim date_info As DateTimeFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat()
            TextBox1.AppendText("Short Date Format = " & date_info.ShortDatePattern & vbNewLine)
            TextBox1.AppendText("Short Time Format = " & date_info.ShortTimePattern & vbNewLine)
            TextBox1.AppendText("Date Separator = " & date_info.DateSeparator & vbNewLine)
            TextBox1.AppendText("Full Date&Time Pattern = " & DateTimeFormatInfo.InvariantInfo().FullDateTimePattern & vbNewLine)
            TextBox1.AppendText("Now as Full Date Time = " & Now.ToString(date_info.FullDateTimePattern & vbNewLine))
            TextBox1.AppendText("Now as Short Date = " & Now.ToString(date_info.ShortDatePattern & vbNewLine))
            TextBox1.AppendText("Now as Short Time = " & Now.ToString(date_info.ShortTimePattern & vbNewLine))
            TextBox1.AppendText("Now as Invariant Full Date & Time = " & Now.ToString(DateTimeFormatInfo.InvariantInfo().FullDateTimePattern & vbNewLine))
        End Sub


    Monday, September 24, 2012 3:00 AM
  • Dear Sid,

    till time you have not give a single reply about your issue status,

    pls. always be aware for your thread!


    Pl. Mark/Proposed as Answer if found your solution Vote as Helpful if related to your topic. Always Motivate others by performing this Action.

    • Edited by ArifMustafa Monday, September 24, 2012 7:00 PM
    Monday, September 24, 2012 5:34 AM