Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert mm/dd/yyyy to yyyymmdd (VB.NET)

Is there any way I can convert a date of format: dd/mm/yyyy to yyyymmdd format? For example from : 25/07/2011 to 20110725? in VB.NET?

like image 345
l3_08 Avatar asked Jul 28 '11 12:07

l3_08


People also ask

How do I fix string is not recognized as a valid DateTime in VB net?

[FormatException: String was not recognized as a valid DateTime.] then it is telling you that whatever is in the text box cannot be recognised as a date. You need to either change the textbox contents so it is a valid date, or provide a custom date format for the date parser that matches the text box contents, or both.


2 Answers

Dates themselves don't have formats inherently. You can parse a string into a DateTime by parsing it with dd/MM/yyyy format and then convert that into a string using yyyyMMdd format:

DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
                                    CultureInfo.InvariantCulture);

string reformatted = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture);

Or in VB:

Dim date as DateTime = DateTime.ParseExact(text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Dim reformatted as String = date.ToString("yyyyMMdd", CultureInfo.InvariantCulture)

(And make sure you have an import for System.Globalization.)

However, ideally you should keep it as a DateTime (or similar) for as long as possible.

like image 73
Jon Skeet Avatar answered Oct 09 '22 18:10

Jon Skeet


 CDate(Datetext).ToString("yyyyMMdd")
like image 39
Ritz Arlekar Avatar answered Oct 09 '22 18:10

Ritz Arlekar