开发者

how to get date from string like this?

I want to extract the date from string like this :

"HTTP test [17] 20110515150601.log"

and I want to know if this date is valid or not

tha开发者_JAVA百科nks.


This is a small sample app that shows how to parse the date. It is easily customized to parse the time as well if you know the format

static void Main(string[] args)
        {
            string source = "HTTP test [17] 20110515150601.log";
            Regex regex = new Regex(@"(\d{8})\d*\.log");
            var match = regex.Match(source);
            if (match.Success)
            {
                DateTime date;
                if (DateTime.TryParseExact(match.Groups[1].Value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                {
                    Console.WriteLine("Parsed date to {0}", date);
                }
                else
                {
                    Console.WriteLine("Could not parse date");
                }
            }
            else
            {
                Console.WriteLine("The input is not a match.");
            }
            Console.ReadLine();
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜