C# 查找字符串是否包含日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14917203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding if a string contains a date and time
提问by Boardy
I am working on a project where I am reading in a file which could come in two different formats, one includes a date and time and the other doesn't.
我正在做一个项目,我正在读取一个文件,该文件可能有两种不同的格式,一种包含日期和时间,另一种不包含。
When I read in the first line I need to check whether the string contains the date and time or not and read the file and based on the check read the file in a certain way.
当我阅读第一行时,我需要检查字符串是否包含日期和时间并读取文件并根据检查以某种方式读取文件。
I'm guessing this would be some kind of regular expression but have no idea where to start and can't find anything relevant.
我猜这将是某种正则表达式,但不知道从哪里开始,也找不到任何相关内容。
Thanks for any help you can provide.
感谢您的任何帮助,您可以提供。
UPDATEI don't think I've been very clear as to what I am asking. When I read the log file line by line the line may come in as:
更新我不认为我已经很清楚我在问什么。当我逐行读取日志文件时,该行可能会出现:
Col1 Col2 Col3 Col4 Col5
Sometimes the line may come in as
有时线路可能会作为
Col1 17-02-2013 02:05:00 Col2 Col3 Col4 Col5
When I read the line I need to do a check whether there is a date and time string contained within the string.
当我阅读该行时,我需要检查字符串中是否包含日期和时间字符串。
采纳答案by Tonix
If the format of the date has been defined, you can use Regex to solve it.
如果已经定义了日期的格式,可以使用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();
}
}
}
回答by amhed
Update 2: Found out using DateTime.TryParseExact is a much better way that using Regex Expressions
更新 2:发现使用 DateTime.TryParseExact 是使用 Regex 表达式的更好方法
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
}
回答by xameeramir
This worked for us:
这对我们有用:
If the string value is a valid datetime value, then it will not give any exception:
如果字符串值是有效的日期时间值,则不会给出任何异常:
try
{
Convert.ToDateTime(string_value).ToString("MM/dd/yyyy");
}
If the string value is an invalid datetime value, then it will give exception:
如果字符串值是无效的日期时间值,则会给出异常:
catch (Exception)
{
}
回答by Syed Faizan Ali
Use this method to check if string is date or not:
使用此方法检查字符串是否为日期:
private bool CheckDate(String date)
{
try
{
DateTime dt = DateTime.Parse(date);
return true;
}
catch
{
return false;
}
}
回答by Arnold_john
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);
}