user1884709
user1884709

Reputation: 145

Issue in Converting Date Time c#

I am facing an issue when converting the datetime

var date = DateTime.Now;
txtdate.Text = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

//I need to pass it later to as a DateTime variable. When i re-convert it gives me an error)

DateTime dtReconvert =Convert.toDateTime(txtdate.Text);  //Error String was not recognized as a valid DateTim

When i set the datetime to something like "01/01/2013" and convert it to Date Time it not giving me any error.

Upvotes: 1

Views: 1219

Answers (2)

Clinton Ward
Clinton Ward

Reputation: 2511

try this

DateTime.ParseExact(txtdate.Text, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)

or

Convert.ToDateTime(txtdate.Text, CultureInfo.InvariantCulture)

Microsoft have adopted MM/dd/yyyy as a culture-agnostic format, it's an ambiguous format which isn't something that I would want to build a large system on.

Upvotes: 1

Habib
Habib

Reputation: 223237

Use DateTime.ParseExact with the format "dd/MM/yyyy"

DateTime dtObject = DateTime.ParseExact(txtdate.Text, 
                                        "dd/MM/yyyy", 
                                        CultureInfo.InvariantCulture);

Upvotes: 8

Related Questions