Question

The user is supposed to enter date in format: %m %d %Y

What I need to do is convert the date to: 11 11 2013 ( which is today`s date). I have not worked much with dates. Is there some method that does this conversion out of the box? I looked through DateTime options but couldn't find what I need.

Edit:

From the answers received it seems that it is not very clear what I am asking.

In our software the user can insert dates in format like this:

http://ellislab.com/expressionengine/user-guide/templates/date_variable_formatting.html

I am trying to parse this user input and return the today date. So from the link above:

%m - month - “01” to “12”

%d - day of the month, 2 digits with leading zeros - “01” to “31”

%Y - year, 4 digits - “1999”

I was wondering if there is a method that takes %m %d %Y as an input and returns the corresponding today date in the specified format ( which is 11 11 2013 today). Or at least something close to that. Hope it is more clear now.

EDIT 2:

After digging a little bit more I found that what I am looking for is an equivalent of C++ strftime in C#.

http://www.cplusplus.com/reference/ctime/strftime/

But for some reason I cannot see an example this to implemented in C#.

Était-ce utile?

La solution 2

My go-tos for DateTime Input and Output:

http://www.dotnetperls.com/datetime-parse for input (parsing)

http://www.csharp-examples.net/string-format-datetime/ for output (formatting)

string dateString = "01 01 1992";
string format = "MM dd yyyy";

DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

Edit since his edit makes my above answer irrelevant (but will leave there for reference):

From what you're saying, you want to output today's date in a dynamically-defined format?

So if I want to see month, date, year, I say "MM dd YY" and you return it to me?

If so:

DateTime dt = DateTime.Today; // or initialize it as before, with the parsing (but just a regular DateTime dt = DateTime.Parse() or something quite similar)

Then

String formatString = "MM dd YY";
String.Format("{0:"+ formatString+"}", dt);

Your question is still quite unclear, though.

Autres conseils

You can use DateTime.TryParseExact to parse a string to date and DateTime-ToString to convert it back to string with your desired format:

DateTime parsedDate;
if (DateTime.TryParseExact("11 11 2013", "MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{ 
    // parsed successfully, parsedDate is initialized
    string result = parsedDate.ToString("MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture);
    Console.Write(result);
}

Use ParseExact:

var date = DateTime.ParseExact("9 1 2009", "M d yyyy", CultureInfo.InvariantCulture);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top