【问题标题】:Finding if a string contains a date and time查找字符串是否包含日期和时间
【发布时间】:2013-02-17 01:47:17
【问题描述】:

我正在做一个项目,我正在读取一个文件,该文件可能有两种不同的格式,一种包含日期和时间,另一种不包含。

当我在第一行读取时,我需要检查字符串是否包含日期和时间并读取文件并根据检查以某种方式读取文件。

我猜这将是某种正则表达式,但不知道从哪里开始,也找不到任何相关内容。

感谢您提供的任何帮助。

更新 我不认为我已经很清楚我在问什么。当我逐行读取日志文件时,该行可能如下所示:

Col1   Col2  Col3  Col4  Col5 

有时这条线可能会进来

Col1  17-02-2013 02:05:00 Col2  Col3  Col4  Col5

当我阅读该行时,我需要检查字符串中是否包含日期和时间字符串。

【问题讨论】:

  • 你能分享一下你尝试过的吗?
  • @Boardy:您知道这些潜在日期将以哪种日期时间语言环境格式显示吗? dd-mm-yyyy hh:mm:ss 总是?
  • @bob-the-destroyer 它应该始终采用 dd-mm hh:mm:ss 的格式。我认为格式没有变化(请注意,不包括年份)。我之前忘记提了
  • @Boardy:您还能在该列中发现哪些其他额外的文本会阻止使用TryParse() 将其正确解析为日期时间?
  • 我要检查整个字符串,看看它是否包含日期/时间字符串。如果是这样,然后我遍历字符串并将每一列放入一个变量中,包括变量,否则我遍历每一列而不必担心日期和时间。否则我不知道是 5 列(无日期)还是 6 列(有日期)

标签: c#


【解决方案1】:

如果日期的格式已经定义好了,可以用Regex来解决。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace RegTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string testDate = "3214312402-17-2013143214214";
            Regex rgx = new Regex(@"\d{2}-\d{2}-\d{4}");
            Match mat = rgx.Match(testDate);
            Console.WriteLine(mat.ToString());
            Console.ReadLine();
        }
    }
}

【讨论】:

  • 我稍微改进了正则表达式示例
  • 非常感谢您的帮助,非常感谢。
【解决方案2】:

更新 2:发现使用 DateTime.TryParseExact 比使用正则表达式更好

DateTime myDate;
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
    //String has Date and Time
}
else
{
    //String has only Date Portion    
}

【讨论】:

  • 我认为 OP 想要检查日期和时间 :)
  • @scartag:如果xdatetime == DateTime.MinValue,表示尝试失败。幸运的是,如果 DateTime.TryParse(x) 失败,它会返回 false,因此您无需担心这个最小值检查。
  • 如果 TryParse 失败,DateTime 对象将保持默认值(即 DateTime.MinValue)。
  • @amhed:如果DateTime.TryParse(x) 成功与否返回布尔值,则无需检查最小值。也就是说,如果它没有成功,它总是会返回 false。
  • 哦,我明白你的意思了。我也可以使用 if DateTime.TryParse(inputString, out myDate) 并保存一行代码。谢谢!
【解决方案3】:
   string s = " Subject: Current account balances for 21st December 2017 and 2nd January 2019 mnmnm ";//here is u r sample string

   s = s.ToLower();
   string newStrstr = Regex.Replace(s, " {2,}", " ");//remove more than whitespace
   string newst = Regex.Replace(newStrstr, @"([\s+][-/./_///://|/$/\s+]|[-/./_///://|/$/\s+][\s+])", "/");// remove unwanted whitespace eg 21 -dec- 2017 to 21-07-2017
   newStrstr = newst.Trim();
   Regex rx = new Regex(@"(st|nd|th|rd)");//21st-01-2017 to 21-01-2017
   string sp = rx.Replace(newStrstr, "");
   rx = new Regex(@"(([0-2][0-9]|[3][0-1]|[0-9])[-/./_///://|/$/\s+]([0][0-9]|[0-9]|[1][0-2]|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|january|february|march|april|may|june|july|augu|september|october|november|december)[-/./_///:/|/$/\s+][0-9]{2,4})");//a pattern for regex to check date format. For August we check Augu since we replaced the st earlier
   MatchCollection mc = rx.Matches(sp);//look for strings that satisfy the above pattern regex

   List<DateTime> dates=new List<DateTime>(); //Create a list to store the detected dates

   foreach(Match m in mc)
   {
        string s2=Regex.Replace(m.ToString(), "augu", "august");
        dates.Add(DateTime.Parse(s2);
   }

【讨论】:

  • 这将在任何条件下从字符串中获取日期
【解决方案4】:

使用此方法检查字符串是否为日期:

private bool CheckDate(String date)
{
    try
    {
        DateTime dt = DateTime.Parse(date);
        return true;
    }
    catch
    {
        return false;
    }
}

【讨论】:

  • 虽然代码很受欢迎,但它应该总是有一个附带的解释。这不必很长,但在意料之中。
  • 我已经记下了您的建议。谢谢
【解决方案5】:

这对我们有用:

如果字符串值是有效的日期时间值,那么它不会给出任何异常:

try
{
    Convert.ToDateTime(string_value).ToString("MM/dd/yyyy");
}

如果字符串值是一个无效的日期时间值,那么它会给出异常:

catch (Exception)
{
}

【讨论】:

  • 虽然代码很受欢迎,但它应该始终有一个附带的解释。这不必很长,但在意料之中。
  • 我不太了解你,如果你以不需要我的后期修复的方式做到了,你就得到了我的支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多