l3_08
l3_08

Reputation: 191

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?

Upvotes: 9

Views: 108016

Answers (4)

user16412696
user16412696

Reputation: 1

Public Function DateFormateYYYYMMDD(ByVal Dtp As DateTimePicker) As String

   Try
      Dim StrDate, StrYear, StrMonth, StrDay As String
      StrDate = FormatDateTime(Dtp.Value, DateFormat.ShortDate)
      StrMonth = Month(Dtp.Value)
      StrDay = Convert.ToString(Dtp.Value.Day)
      StrYear = Year(Dtp.Value)
      StrDate = StrYear + "-" + StrMonth + "-" + StrDay

      Return StrDate
   Catch ex As Exception

   End Try
End Function

this function can be used to convert datetime picker value format to yyyyMMdd

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504162

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.

Upvotes: 15

Ritz Arlekar
Ritz Arlekar

Reputation: 385

 CDate(Datetext).ToString("yyyyMMdd")

Upvotes: 7

Vincent Van Den Berghe
Vincent Van Den Berghe

Reputation: 5575

Use the DateTime.ParseExact method to parse the date, then use DateTimeObj.ToString("yyyyMMdd").

DaTeTime.ParseExact

Upvotes: 0

Related Questions