解析文件名的日期 [英] Parse through date of a filename

查看:90
本文介绍了解析文件名的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要解析一个文件名的日期。到目前为止,我有一个文件,日期是

So I need to parse through a date of a filename. So far example I have a file and the date is

Accounts_2012017

我目前遇到的问题是日期格式类似于M / dd / yyyy等等每次我使用ParseExact,

我得到一个错误,即字符串不是有效的DateTime,即使我做MM / dd / yyyy。我还有哪些选择可以选择这个日期?



以上日期内容为:2017年2月1日



我尝试过:



The problem I have at the moment is the format of the date is something like "M/dd/yyyy" and so every time I use ParseExact,
I get an error that the string is not a valid DateTime, even if I do "MM/dd/yyyy". What are my other options to pick this date out?

The above date reads as: February 1st 2017

What I have tried:

string temp = filename.Replace(".txt", "").Substring(filename.LastIndexOf('_') + 1);
           DateTime extracted = DateTime.ParseExact(temp, "Mddyyyy", System.Globalization.CultureInfo.InvariantCulture);

推荐答案

根据您发布的示例文件名,您的格式字符串不正确。它应该是yyyyMdd。顺便说一句,如果改变它还为时不晚,那么如果你使用两位数的月份会更好。这样,对于日期是什么并没有混淆,你的解析将始终有效。



我个人认为你不会可靠地解析日期,因为您允许月份由一个数字表示。要减轻文件名的这一方面,您可以检查表示日期的字符串的长度,如果它小于8,则在其前面添加零。此时,您可以将格式字符串更改为MMddyyyy,并且每次都会正确解析(假设当天总是用两位数表示)。



FWIW,您还应考虑将该声明分解为不连续的部分,以便您可以更轻松地更正日期(并处理错误)。
According to the example filename you posted, your format string is incorrect. It should be "yyyyMdd". BTW, if it's not too late to change it, it would be better if you used a two-digit month. That way, there's no confusion about what the date is, and your parsing will always work.

I don't personally think you'll be able to reliable parse the date because you're allowing the month to be represented by a single digit. To mitigate that aspect of the filename, you could check the length of the string that represents the date, and if it's less than 8, prepend it with a zero. At that point, you could change your format string to "MMddyyyy", and it will parse correctly every time (assuming, of course that the day is always represented by two digits).

FWIW, you should also consider breaking that statement up into discrete parts so you can correct the date (and handle errors) more easily.


试试这个

它适用于 MMddyyyy Mddyyyy



try this
it will work for "MMddyyyy" and "Mddyyyy"

string filename = "Accounts_2012017.txt";
           string temp = filename.Replace(".txt", "").Substring(filename.LastIndexOf('_') + 1);
           string format = (temp.Length == 7) ? "Mddyyyy" : "MMddyyyy";
           DateTime extracted = DateTime.ParseExact(temp, format, System.Globalization.CultureInfo.InvariantCulture);


这篇关于解析文件名的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆