1

I have a string with a date in this format. "24-11-2015" or "dd-MM-yyyy". I need to convert this to a date with this format. "2015-11-24" or "yyyy-MM-dd". I've tried several ways, and all of them rely on my system format for this to work. If i run my program on a computer with english time format this works.

Date.ParseExact("24-11-2015", "dd-MM-yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)

But if i run it on a computer running danish format i get error because there is no 24th month. How do i make the date format independent of my system time format.

3
  • DateTime variables have no formats. It is their representation as strings that give them 'a format'. It is not clear from your question if you have a string representing a date and you want to parse it into a DateTime variable or if you have a DateTime variable and want it to be shown in a particular way Commented Apr 5, 2016 at 18:22
  • Also if this is a desktop app, TryParse can be used to test all possible formats used by the current culture...and some cultures have over 100. Commented Apr 5, 2016 at 19:48
  • If the user can enter the complete string directly you are in trouble. The system can't tell the difference between the m-d-yyyy and d-m-yyyy reliably. You need to use separate fields or a date picker. Commented Apr 5, 2016 at 22:51

1 Answer 1

4

Solution:

Dim dateTime As String = "24-11-2015"
Dim dt As DateTime = Convert.ToDateTime(dateTime)
Console.WriteLine("{0}-{1}-{2}", dt.Year, dt.Month.ToString("D2"), dt.Day.ToString("D2"))

Solution 2:

Dim dateTime As String = "24-11-2015"
Dim dt As DateTime = Convert.ToDateTime(dateTime)
Dim format As String = "yyyy-MM-dd"
Dim str As String = dt.ToString(format)
Console.WriteLine(str)

You can also try Formatting Date and Time for a Specific Culture.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.