Althaf Ahamed
Althaf Ahamed

Reputation: 51

How to use culture for changing the datetime format

I want to change the date format

CultureInfo ci = new CultureInfo("en-US");

Thread.CurrentThread.CurrentCulture = ci;

string fromdate =(TxtFrom.Text);

string todate = (TxtTo.Text);

DateTime dt =DateTime.Parse(fromdate);

DateTime d =DateTime.Parse(todate);

_DivAPath.FROM_DATE = Convert.ToDateTime("d",ci);

_DivAPath.TO_DATE = Convert.ToDateTime("d",ci);

But it will show exception that the given Datetime is not a correct format.how to change the datetime function...

please explain

Upvotes: 2

Views: 167

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460370

First, you don't need to actually change the culture if you want to parse or convert dates with a given CultureInfo, so this is unnecessary:

Thread.CurrentThread.CurrentCulture = ci;

You can simply use the DateTime.Parse overload that accepts the culture:

DateTime dt = DateTime.Parse(fromdate, ci); 

The exception is probably raised at Convert.ToDateTime("d",ci); since d is not a valid date ;)

Maybe FROM_DATE is a string property and you actually want to convert the datetime to a short-date-string, then you could either use:

_DivAPath.FROM_DATE = dt.ToString("d", ci);

or

_DivAPath.FROM_DATE = dt.ToShortDateString(); // uses the current-culture

Upvotes: 2

Alexander
Alexander

Reputation: 2477

You are passing the String "d" as a value to convert to DateTime. Pass d and dt without the quotation marks.

Upvotes: 0

Related Questions