2

How to convert 04/09/2013 8:09:10 PM to 09/04/2013 (MM-dd-yyyy). I tried to convert but it is taking 09 as date and 04 as month.

Please help

[HttpPost]
public string getdailynote(DateTime selectedDate)
//selectedDate gets date as 04/09/2013 8:09:10 PM
{
    string x = selectedDate.ToString("MM-dd-yyy", CultureInfo.InvariantCulture);
    string daily;
    DateTime dt = Convert.ToDateTime(x);
    //dt gets value as {09/04/2013 12:00:00 AM} but 09 as date and 04 as month
    Dnote.RealDate =dt;
    daily = _scheduler.GetDailyNote(Dnote);
    return daily;
}
5

3 Answers 3

5

it is taking 09 as date and 04 as month

Yes, because you have said it, change

"MM-dd-yyy"

to

"dd/MM/yyyy h:mm:ss tt"

DateTime.ParseExact("04/09/2013 8:09:10 PM","dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

Demo

Now, if you want to convert it to string with this format MM-dd-yyyy:

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

Comments

2

Use

DateTime.ParseExact(x , "MM-dd-yyy", CultureInfo.InvariantCulture);

Comments

1

When you convert from DateTime to string you use an overload of the instance method ToString where you can specify a format string, and that is fine.

But then when you convert in the other direction, you shouldn't use Convert.ToDateTime method. Instead use DateTime.ParseExact or DateTime.TryParseExact because with them you can again specify the format string you want (and the format provider (culture)).

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.