2

How to convert any date format to a specified format in C#.

For example:

If Date Format is

14.11.2011 or 14/11/2011 

Looking for a conversion function which converts into

yyyy-MM-dd format like 2011-11-14
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Suave Nti
  • 3,721
  • 11
  • 54
  • 78
  • 3
    Have you tried to search even a BIT?! [tag:DateTime](http://stackoverflow.com/questions/tagged/datetime), [tag:DateTime-Format](http://stackoverflow.com/questions/tagged/datetime-format) – abatishchev Jan 23 '12 at 08:15

4 Answers4

9

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
  • Thanks Andrew, Appreciate your kind time to anwser rather than downvoting :) – Suave Nti Jan 23 '12 at 08:27
  • 1
    @DarkRider You are welcome. However, three things: 1) Don't make assumptions about who voted up/down based on comments/answers. It's very possible *I* did down vote, and abatishchev did not. 2) Don't take down votes personally. 3) You could, possibly, have found an answer more quickly by searching. (although in this specific case, you did get a few answers *very* fast...) – Andrew Barber Jan 23 '12 at 08:31
  • Thanks andrew, But times downvote will discourage a fresher to ask a question in SO. such in my case :) – Suave Nti Jan 23 '12 at 08:37
  • 1
    @DarkRider You are exactly right in a way: Down votes discourage the questions that get down voted. *That is exactly intended*. I've been down voted plenty of times; I learn from it. – Andrew Barber Jan 23 '12 at 08:39
3

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
archil
  • 39,013
  • 7
  • 65
  • 82
  • 2
    Correct; The question is also asking about parsing, though. Or at least it seems logical to assume that, since it talks about an existing date format (which does not apply if you already have a `DateTime` object.) – Andrew Barber Jan 23 '12 at 08:18
0
string s = "May 29,2012";
DateTime dt;
DateTime.TryParse(s, out dt);

Response.Write(dt.ToString("MM/dd/yyyy"));
Botz3000
  • 39,020
  • 8
  • 103
  • 127
Vinoth
  • 1
0

You can use the DateTime.Parse or DateTime.ParseExact methods to parse the string into a DateTime then you can use the DateTime.ToString() to return the date in the new format. For standard formatting check this page for custom date formats this

tbt
  • 718
  • 5
  • 7