0
votes

I'm using VS 2013 and VB language

My task is to store a user entered date in the format mm/dd/yyyy

    Dim date1 As String = Format("MM/dd/yyyy")
    Dim date2 As Date
    Dim date3 As Date

    date1 = Console.ReadLine()
    date2 = DateTime.Now
    date3 = DateTime.Parse(date1)


    Console.ReadLine()

I first tried entering the date as Dim date1 as Date, but entering it in mm/dd/yyyy is invalid format.

So I tried this method, and get the error "String was not recognized as a valid DateTime"

How can I format the entered date so that it will be recognized as a valid datetime?

Thanks

2

2 Answers

2
votes

User cannot be forced to enter the date in the format that you expect (particularly on a console application). So your best line of action is trying to parse this date and inform your user that the input is invalid

 Dim isValid = False
 Dim dt As DateTime
 While(Not isValid)
    Console.WriteLine("Please enter a date in the format MM/dd/yyyy")
    Dim input = Console.ReadLine()
    isValid = DateTime.TryParseExact(input, "MM/dd/yyyy", _
                       CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
 End While

DateTime.TryParseExact is a method of the DateTime that tries to parse the input string accordingly to a format specified. If the string complies to the format required then the method returns true and the last parameter is set to the datetime resulting from the conversion. Otherwise the method return false without throwing an exception so you could take the appropriate measures (in this case request again the input)

0
votes

All dates are stored in memory as dates, and do not actually have formats. The formats appear when you change the date into a string (i.e. with the Date.ToString() method).

I think the best option here is to use Date.Parse() with no arguments, so that the command-line will accept all date formats (be prepared to catch format exceptions), and then when you need to display the date back to the user, format it using a format string and the Date.ToString() method.

Code example follows:

    Dim strDateFormat = "MM/dd/yyyy"
    Dim date2 As Date
    Dim date3 As Date

    date2 = Now()
    date3 = Date.Parse(Console.ReadLine())

    Console.WriteLine(date3.ToString(strDateFormat))

P.S. As you have it written, the command input overwrites your formatting string, so your formatting string is effectively useless.