user42348
user42348

Reputation: 4319

Date Time Conversion

I want to convert mm/dd/yyyy to dd/mm/yyyy. My application is asp.NET with VB. I tried following code

DateTime.Parse(oldDate.ToString("dd\mm\yyyy"))

But got the error:

"The string was not recognized as a valid dateTime. There is an unknown word starting at index 2"

Can any one give the appropriate code?

Upvotes: 1

Views: 1446

Answers (3)

dbasnett
dbasnett

Reputation: 11773

if oldDate is a DateTime then all you need to do is

    Dim oldDate As DateTime = DateTime.Now

    Dim odS As String 'old date as string
    odS = oldDate.ToString("ddMMyyyy").Insert(4, "\").Insert(2, "\")

changing the string format does not change the DateTime. DateTime's are numbers, not strings.

Upvotes: 0

LukeH
LukeH

Reputation: 269658

In VB:

Dim dt As DateTime = _
    DateTime.ParseExact(oldDate, "MM/dd/yyyy", CultureInfo.InvariantCulture)

' and then if you want to format it in dd/MM/yyyy format
Dim s As String = dt.ToString("dd/MM/yyyy")

In C#:

DateTime dt =
    DateTime.ParseExact(oldDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

// and then if you want to format it in dd/MM/yyyy format
string s = dt.ToString("dd/MM/yyyy");

Upvotes: 4

Gerrie Schenck
Gerrie Schenck

Reputation: 22378

You should escape the \ characters.

Upvotes: 0

Related Questions