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;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gs11111
  • 649
  • 2
  • 17
  • 49

3 Answers3

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);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Use

DateTime.ParseExact(x , "MM-dd-yyy", CultureInfo.InvariantCulture);
speti43
  • 2,886
  • 1
  • 20
  • 23
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)).

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181