C# 如何从字符串中仅获取日期和时间?

C# 如何从字符串中仅获取日期和时间?,c#,winforms,C#,Winforms,在表格1中,我有: satelliteMapToRead = File.ReadAllText(localFilename + "satelliteMap.txt"); 然后在构造函数中: ExtractImages.ExtractDateTime("image2.ashx?region=eu&time=", "&ir=true", satelliteMapToRead); 在ExtractImages类中,我有: public static void ExtractDate

在表格1中,我有:

satelliteMapToRead = File.ReadAllText(localFilename + "satelliteMap.txt");
然后在构造函数中:

ExtractImages.ExtractDateTime("image2.ashx?region=eu&time=", "&ir=true", satelliteMapToRead);
在ExtractImages类中,我有:

public static void ExtractDateTime(string firstTag, string lastTag, string f)
{
    int index = 0;
    int t = f.IndexOf(firstTag, index);
    int g = f.IndexOf(lastTag, index);
    string a = f.Substring(t, g - t);
}
这是文本文件中字符串的示例:

图2.ashx?区域=欧盟和时间=20130902145和ir=真

从这个字符串中,我希望变量g只包含:201309202145 然后将变量a转换为日期时间:日期2013 09 20-时间21 45

现在我在变量a中得到的是:

图2.ashx?地区=欧盟和时间=20130922215


而且这不是我所需要的。

既然您已经这样做了,请再次使用
indexOf(“time=”)
获取
20130922215
。那么日期/时间由

DateTime.ParseExact(str, "yyyyMMddhhmmss", CultureInfo.InvariantCulture);
将此线路切换到:

int t = f.IndexOf(firstTag, index) + firstTag.Length;

IndexOf
返回字符串第一个字符的位置。所以在你的例子中,
t
实际上是零。这就是为什么
a
中也有第一个标记。

您没有考虑
第一个标记的长度:

int t = f.IndexOf(firstTag, index) + firstTag.Length;
没有错误处理(缺少参数或格式无效):


Omada现在使用您的行变量a contain:20130922215&ir=true“,”/image2.ashx?regEd这确实有效:int index=0;intt=f.IndexOf(firstTag,index)+firstTag.Length;int g=f.IndexOf(lastTag,index);字符串a=f.子字符串(t,g-t);Zong Zheng i did:DateTime dt=DateTime.ParseExact(a,“yyyyMMddhhmmss”,CultureInfo.InvariantCulture);变量a现在包含20130922215,但我收到一个错误/异常:FormatException:String未被识别为有效的日期时间
string url = "image2.ashx?region=eu&time=201309202145&ir=true";
var queryString = System.Web.HttpUtility.ParseQueryString(url);
DateTime dt = DateTime.ParseExact(queryString["time"], "yyyyMMddHHmm", CultureInfo.InvariantCulture);