DateTime.TryParse() === using System; using System.Globalization;namespace Parse { class Class1 { public static void Main(string[] args) { // Assume the current culture is en-US. // The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. string myDateTimeValue = "2/16/1992 12:15:12"; DateTime myDateTime = DateTime.Parse(myDateTimeValue); Console.WriteLine("1) myDateTime = {0}", myDateTime);// Reverse month and day to conform to a different culture. // The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. IFormatProvider culture = new CultureInfo("fr-FR", true); string myDateTimeFrenchValue = " 16/02/1992 12:15:12"; DateTime myDateTimeFrench = DateTime.Parse(myDateTimeFrenchValue, culture, DateTimeStyles.NoCurrentDateDefault); Console.WriteLine("2) myDateTimeFrench = {0}", myDateTimeFrench);
// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. string[] expectedFormats = {"G", "g", "f" ,"F"}; myDateTimeFrench = DateTime.ParseExact(myDateTimeFrenchValue, expectedFormats, culture, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine("3) myDateTimeFrench = {0}", myDateTimeFrench); } } } /* This example yields the following results:1) myDateTime = 2/16/1992 12:15:12 PM 2) myDateTimeFrench = 2/16/1992 12:15:12 PM 3) myDateTimeFrench = 2/16/1992 12:15:12 PM */
===
using System;
using System.Globalization;namespace Parse
{
class Class1
{
public static void Main(string[] args)
{
// Assume the current culture is en-US.
// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. string myDateTimeValue = "2/16/1992 12:15:12";
DateTime myDateTime = DateTime.Parse(myDateTimeValue);
Console.WriteLine("1) myDateTime = {0}", myDateTime);// Reverse month and day to conform to a different culture.
// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. IFormatProvider culture = new CultureInfo("fr-FR", true);
string myDateTimeFrenchValue = " 16/02/1992 12:15:12";
DateTime myDateTimeFrench =
DateTime.Parse(myDateTimeFrenchValue,
culture,
DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine("2) myDateTimeFrench = {0}", myDateTimeFrench);
// The date is Feburary 16, 1992, 12 hours, 15 minutes and 12 seconds. string[] expectedFormats = {"G", "g", "f" ,"F"};
myDateTimeFrench =
DateTime.ParseExact(myDateTimeFrenchValue,
expectedFormats,
culture,
DateTimeStyles.AllowWhiteSpaces);
Console.WriteLine("3) myDateTimeFrench = {0}", myDateTimeFrench);
}
}
}
/*
This example yields the following results:1) myDateTime = 2/16/1992 12:15:12 PM
2) myDateTimeFrench = 2/16/1992 12:15:12 PM
3) myDateTimeFrench = 2/16/1992 12:15:12 PM
*/
DateTime vDateTime = DateTime.ParseExact(S, "yyyyMMddHHmmss", null,
System.Globalization.DateTimeStyles.None);
Console.WriteLine(vDateTime);
string S = "20070723122743";
DateTime dt = DateTime.ParseExact(S, "yyyyMMddHHmmss", null);
DateTime dt = DateTime.ParseExact("20070723122743", "yyyyMMddhhmmss", System.Globalization.CultureInfo.CurrentCulture);
挺好的!