-1

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

字符串如下:

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

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

4

3 回答 3

3

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

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

先自己试一试。如果您遇到问题,请更新您的问题以显示您正在尝试的代码,有人会进一步帮助您。

...

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

string s = // your string as in the question

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

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

于 2013-06-27T23:01:29.337 回答
1

更新我假设 FTP 列表的文件显示有一个固定的结构,所以你可以简单地使用String.Substring来提取日期时间字符串,然后解析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

var datetime = DateTime.ParseExact(dateString + timeString,"yyyyMMddHHmmss",null);
于 2013-06-27T22:59:08.900 回答
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);
于 2013-06-27T23:40:40.423 回答