从字符串中提取复杂的日期/时间格式

时间:2013-06-27 22:55:10

标签: c# string datetime

我正在尝试找到提取日期和时间字符串的最佳方法,该字符串以非常奇怪的格式存储在从FTP文件列表中检索的文件名(字符串)中。

字符串如下:

-rwxr-xr-x    1 ftp      ftp        267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r

我想要提取的具体数据是20130606_021303021303的格式为小时,秒和毫秒。 DateTime.Parse和DateTime.ParseExact不愿意合作。关于如何启动并运行的任何想法?

3 个答案:

答案 0 :(得分:3)

您似乎已经获得了文件列表的整行,包括权限,用户,所有者,文件大小,时间戳和文件名。

您要求的数据似乎只是文件名的一部分。首先使用一些基本的字符串操作(SplitSubstring等)。然后,如果您只有日期时间部分,则可以拨打DateTime.ParseExact

首先尝试一下。如果您遇到问题,请更新您的问题以显示您正在尝试的代码,并且有人会帮助您。

...

哦,好的。有没有搞错。我感觉很慷慨。这是一个单行:

string s = // your string as in the question

DateTime dt = DateTime.ParseExact(string.Join(" ", s.Split('_', '.'), 1, 2),
                                  "yyyyMMdd HHmmss", null);

但请下次,先自己尝试一下。

答案 1 :(得分:1)

UPDATE 我假设FTP列表的文件显示有一个固定的结构,所以你可以简单地使用String.Substring来提取日期时间字符串,然后用{{1 }}:

DateTime.ParseExact

<小时/> 原始答案

使用正则表达式。请尝试以下方法:

var s = "-rwxr-xr-x    1 ftp      ftp        267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r";
var datetime = DateTime.ParseExact(s.Substring(72,15),"yyyyMMddHHmmss",null);

并使用var s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r"; /* The following pattern means: \d{8}) 8 digits (\d), captured in a group (the parentheses) for later reference _ an underscore (\d{6}) 6 digits in a group \. a period. The backslash is needed because . has special meaning in regular expressions .* any character (.), any number of times (*) \r carriage return $ the end of the string */ var pattern = @"(\d{8})_(\d{6})\..*\r$"; var match = Regex.Match(s, pattern); string dateString = matches.Groups[1].Value; string timeString = matches.Groups[2].Value; 解析:

ParseExact

答案 2 :(得分:0)

这可能有效:

string s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r";

// you might need to adjust the IndexOf method a bit - if the filename/string ever changes...
// or use a regex to check if there's a date in the given string 

// however - the first thing to do is extract the dateTimeString:
string dateTimeString = s.Substring(s.IndexOf("_") + 1, 15);

// and now extract the DateTime (you could also use DateTime.TryParseExact)
// this should save you the trouble of substringing and parsing loads of ints manually :)
DateTime dt = DateTime.ParseExact(dateTimeString, "yyyyMMdd_hhmmss", null);
相关问题