Re: Safe conversion from string to DateTime
- From: Hans Merkl <hans_merkl@xxxxxxxxx>
- Date: Thu, 5 May 2005 11:30:27 -0400
I have tried DateTime.Parse but it threw an exception on "12 noon".
Hans
On 5 May 2005 07:15:22 -0700, SCDeveloper wrote:
> use DateTime.Parse or DateTime.ParseExact
>
> Parse ignores leading and trailing white space, and unrecognized
> characters if possible, and it fills in missing information with the
> corresponding current date and time values. Parse will throw a
> FormatException, though, if it's unable to decipher the string you send
> to it.
>
> DateTime.Parse will parse a valid date and time from a string. The
> string must contain the representation of a date and time in one of the
> formats described in the DateTimeFormatInfo object.
>
> For DateTime.ParseExact, the string that you pass to it must exactly
> match the format that you specify in the IFormatProvider parameter.
>
> Example for DateTime.Parse
>
> NewDate = DateTime.Parse("10/27/61 08:47");
> NewDate = DateTime.Parse("10/1961");
> NewDate = DateTime.Parse("27 October 1961 8:47 pm");
>
> IFormatProvider format = new
> System.Globalization.CultureInfo("fr-FR", true);
> string[] expectedFormats = {"g", "G", "f", "F"};
>
> // This is DD/MM/YYYY format
> NewDate = DateTime.ParseExact("27/10/1961 08:47:00",
> expectedFormats, format,
> System.Globalization.DateTimeStyles.AllowWhiteSpaces);
> Console.WriteLine("Parsed DD/MM/YY: {0}", NewDate.ToString());
>
>
> Example for DateTime.ParseExact
>
> try
> {
> NewDate = DateTime.ParseExact(
> "10/27/1961",
> expectedFormats,
> format,
> System.Globalization.DateTimeStyles.AllowWhiteSpaces);
> Console.WriteLine(NewDate.ToString());
> }
> catch (Exception e)
> {
> Console.WriteLine(e.Message);
> }
>
> Hope this helps.
>
> SCDeveloper
> http://www.sharingcorner.com
.
- References:
- Safe conversion from string to DateTime
- From: Hans Merkl
- Re: Safe conversion from string to DateTime
- From: SCDeveloper
- Safe conversion from string to DateTime
- Prev by Date: How to Close Form using a custom button control.
- Next by Date: Re: Workaround for the lack of inherited constructors
- Previous by thread: Re: Safe conversion from string to DateTime
- Next by thread: Re: Safe conversion from string to DateTime
- Index(es):
Relevant Pages
|