How to parse string into DateTime?

O

Olav Tollefsen

I have a string containing a time and date string in the following format:

"HH:mm:ss MM/dd/YY" (example "14:34:12 12/31/02")

How do I parse this into a DateTime variable using C#?

Olav
 
P

Paul R

Use the static Parse method on DateTime:

DateTime dateVariable = DateTime.Parse(aString)
 
O

Olav Tollefsen

Thanks!

What if it is formatted like this:

"Time: HH:mm:ss Date: MM/dd/YY" (example "Time: 14:34:12 Date: 12/31/02")

Do I have to split the string and concatenate it first, or can I parse it
directly using a custom format string?

Olav
 
J

Jerry III

Why don't you RTFM? You can pass a format string to DateTime.Parse and
DateTime.ParseExact.

Jerry
 
O

Olav Tollefsen

It's not obvious to me by RTFM how to pass a format string to
DateTime.Parse.

Olav
 
J

Jerry III

This is from the .Net SDK:

The following sample demonstrates the Parse method.

string strMyDateTime = "2/16/1992 12:15:12";

// myDateTime gets Feburary 16, 1992, 12 hours, 15 min and 12 sec.
System.DateTime myDateTime =
System.DateTime.Parse(strMyDateTime);

System.IFormatProvider format =
new System.Globalization.CultureInfo("fr-FR", true);

// Reverse month and day to conform to a different format.
string strMyDateTimeFrench = " 16/02/1992 12:15:12";

// myDateTimeFrench gets Feburary 16, 1992, 12 hours,
// 15 min and 12 sec.
System.DateTime myDateTimeFrench =
System.DateTime.Parse(strMyDateTimeFrench,
format,
System.Globalization.
DateTimeStyles.NoCurrentDateDefault);

string[] expectedFormats = {"G", "g", "f" ,"F"};
// myDateTimeFrench gets Feburary 16, 1992, 12 hours,
// 15 min and 12 sec.
myDateTimeFrench =
System.DateTime.ParseExact(strMyDateTimeFrench,
expectedFormats,
format,
System.Globalization.
DateTimeStyles.AllowWhiteSpaces);

Note the expectedFormats array, just use your own formats (and since you're
not going to be using locale specific formats you can use
CultureInfo.InvariantCulture instead of the french used in the example. And
if you're going to use only one format you can even use the simpler
ParseExact overload, ParseExact(string, string, IFormatProvider).

I do agree that you can't do this with Parse and you have to use ParseExact
(but the example is from Parse).

Jerry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top