从C#中的字符串中获取所有日期

时间:2013-06-13 09:45:31

标签: c# split

我正在使用基于Web的DOTNET应用程序,其中我在数据库中有一个日志列。每当用户在UI上的注释textarea中添加注释时,日期,他的名字以及注释都会附加到数据库中的现有数据中。以下是列具有数据的格式:

04/05/11 17:10:19 (user2):Work Log -
Closing.
03/31/11 09:40:02 (user2):Work Log -
Support provided over phone.
03/31/11 09:39:43 (user1):Work Log –
Awaiting support reply
03/30/11 11:30:08 (user2):Work Log -
Manager notified by standard e-mail communication.
03/30/11 11:29:30 (user1):Work Log -
Emailed support team
03/30/11 11:28:52 (user1):Work Log -
I have an issue with my Xbox.

我现在尝试在输入这些评论时拉出所有日期(只是日期)。我尝试了很多选择但没有帮助。

2 个答案:

答案 0 :(得分:2)

假设您想在C#代码中执行此操作:

Regex splitter = new Regex("[0-9]{2}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");
foreach (Match m in splitter.Matches(theDatabaseValue)) {
    string dateString = m.Groups[0].Value;
    DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yy HH:mm:ss", null);
}

正则表达式方法的好处是你可以扩展它以提取用户:

Regex splitter = new Regex("(?<date>[0-9]{2}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}) \\((?<user>.+)\\)");
foreach (Match m in splitter.Matches(theDatabaseValue)) {
    string dateString = m.Groups["date"].Value;
    DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yy HH:mm:ss", null);
    string user = m.Groups["user"].Value;
    Console.WriteLine("{0} {1}", dt.ToString(), user);
}

因此即使是消息(我还没有完成正则表达式的那部分,因为我不确定你是否在消息之前有换行符,好像你这样做了)。

完成此操作后,您可以创建一个数据库表,其中包含三列,日期,用户,注释,然后使用正则表达式将现有表转换为该表,让您将来的生活变得更轻松!

答案 1 :(得分:0)

您应该重构数据库以将数据存储在三列(DateTime,User,Comment)中,这将极大地提高性能和可用性。

但如果这不是一个选项,您可以使用DateTime.TryParse从字符串中获取值。例如:

        string comment = "04/05/11 17:10:19 (user2):Work Log - Closing.";

        string dateSection = comment.Substring(0, 17);

        DateTime date;

        if (!DateTime.TryParse(dateSection, out date))
        {
            throw new Exception(string.Format("unable to parse string '{0}'", dateSection));
        }