-1

I want to set a date format so that when I'm reading in my text file and converting it to XML there are no complications with the date format. I.e. if I'm reading in a text file that has USA date format or UK date format I don't want any errors occurring.

I have already written code that converts a text file into an XML file and it works fine. However, now I am trying to ensure the birthday format is correct.

If I'm honest I'm not really sure how to do this.

Also, is it possible to do this by using a combobox, so the user selects which format the date is in?

1 Answers1

0

So that you can experiment with how it can work, I suggest that you make a new Windows Forms project, just for now, and put on the form a ComboBox (name it cbDateFormat) and a Button (name it Button4) and use this code:

Public Class Form1

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim str = "1/4/19" ' test data '

        If cbDateFormat.SelectedIndex = -1 Then
            MsgBox("Please select the date format.")
            Exit Sub
        End If

        Dim dateFormat = ""

        Select Case cbDateFormat.Text
            Case "DD/MM/YYYY"
                dateFormat = "d/M/yyyy"
            Case "MM/DD/YYYY"
                dateFormat = "M/d/yyyy"
            Case "DD/MM/YY"
                dateFormat = "d/M/yy"
            Case "MM/DD/YY"
                dateFormat = "M/d/yy"
            Case Else
                Throw New Exception("Date format not found.")
        End Select

        Dim d As DateTime
        If DateTime.TryParseExact(str, dateFormat, Globalization.CultureInfo.InvariantCulture, Nothing, d) Then
            ' d now holds the datetime '
            MsgBox(d.ToString("dd-MMM-yyyy"))
        End If

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cbDateFormat.Items.AddRange({"DD/MM/YYYY", "MM/DD/YYYY", "DD/MM/YY", "MM/DD/YY"})

    End Sub

End Class

It uses DateTime.TryParseExact to be able to parse a string with a user-selected date format.

I used a test date of 1/4/19 deliberately as it could be the 1st of April or January 1st. A test date of 1/1/19 would not be helpful.

Then be sure to write the date in the XML in the format yyyy-MM-dd so that it is unambiguous.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84