Re: How to parse string into DateTime? by Jerry
Jerry
Mon Sep 15 14:19:50 CDT 2003
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
"Olav Tollefsen" <x@y.com> wrote in message
news:esAcwkweDHA.2748@TK2MSFTNGP11.phx.gbl...
> It's not obvious to me by RTFM how to pass a format string to
> DateTime.Parse.
>
> Olav
>
> "Jerry III" <jerryiii@hotmail.com> wrote in message
> news:e5JT56ueDHA.3896@tk2msftngp13.phx.gbl...
> > Why don't you RTFM? You can pass a format string to DateTime.Parse and
> > DateTime.ParseExact.
> >
> > Jerry
> >
> > "Olav Tollefsen" <x@y.com> wrote in message
> > news:uZ1atQueDHA.1764@TK2MSFTNGP09.phx.gbl...
> > > 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
> > >
> > > "Paul R" <robinsonpr@aol.com> wrote in message
> > > news:O$af5LueDHA.2400@TK2MSFTNGP11.phx.gbl...
> > > > Use the static Parse method on DateTime:
> > > >
> > > > DateTime dateVariable = DateTime.Parse(aString)
> > > >
> > > > "Olav Tollefsen" <x@y.com> wrote in message
> > > > news:O$snIHueDHA.368@TK2MSFTNGP12.phx.gbl...
> > > > > 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
> > > > >
> > > > >
> > > >
> > > >
> > >
> > >
> >
> >
>
>