1

I have been trying many different solutions found here but none works. I want to convert the string to the format of dd/MM/yyyy

editField["ExpiryTime"] = "5/19/2011 12:00:00 AM";
DateTime dt = DateTime.ParseExact(editField["ExpiryTime"].ToString(), "dd/MM/yyyy HH:mm:ss tt",  CultureInfo.InvariantCulture);

But I always get an error of invalid System.DateTime. Pleaes help!

3
  • hint: I'm pretty sure 19 is not a month. Commented Oct 17, 2013 at 7:59
  • @Rotem ExpiryTime is in format M/dd/yyyy hh:mm:ss AM|PM Commented Oct 17, 2013 at 8:00
  • Right, will edit it. But what I want to do is convert it to the format dd/MM/yyyy. SO how can I achieve this? thanks~ Commented Oct 17, 2013 at 8:01

2 Answers 2

1

Use CultureInfo.InvariantCulture to avoid culture issues like invalid date separators and this format:

M/dd/yyyy hh:mm:ss tt

Uppercase M is for months, dd are the days, yyyy the four digit years. Lowercase hh are the hours in 12h format(required in combination with AM/PM), mm are the minutes, ss the seconds and tt the AM/PM designator.

string input = editField["ExpiryTime"].ToString(); // "5/19/2011 12:00:00 AM"
DateTime dt = DateTime.ParseExact(input, "M/dd/yyyy hh:mm:ss tt",  CultureInfo.InvariantCulture);

I want to convert the string to the format of dd/MM/yyyy

Then use ToString in the same way, CultureInfo.InvariantCulture forces / as date separator, without it will be replaced with your current culture's date-separator:

string result = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

Comments

0

If you need it as string, then you should try this

var dt = string.Format("{0:dd/MM/yyyy}",DateTime.Now);

Note: Also check your local system date time format. If it mismatches with the used one , still you might experience the same exception..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.