将YYYYMMDD字符串日期转换为datetime值 [英] Convert YYYYMMDD string date to a datetime value

查看:330
本文介绍了将YYYYMMDD字符串日期转换为datetime值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将字符串转换为c#中的DateTime

Possible Duplicate:
Convert string to DateTime in c#

一个问题

我得到一个实际从directoryInfo获取的字符串值。
我想要完成的是将字符串值转换为日期值进行比较。

I got a string value that actually get from directoryInfo. What i wanted to accomplish is to convert the string value to a date value for making comparison.

文件夹名称就是这样的C:\FOLD \20111120
正确的另一个文件夹路径就像这样
C:\FOLD\20111021

The folder name is sample like this C:\FOLD\20111120 and properly another folder path is like this C:\FOLD\20111021

20111120其实是一个日期格式。我试图把它转换成日期格式,做一些比较,决定删除整个目录。

20111120 is actually a date format. I am trying to convert it into date format to made some comparison decide to deleting the whole directory or not.

我想我将粘贴我的代码这里

I think i shall paste my code here

DirectoryInfo dir = new DirectoryInfo(_FolderPath);

foreach (DirectoryInfo f in dir.GetDirectories())
{
     String folderName = f.ToString();
     DateTime ConDt = Convert.ToDateTime(folderName);
     Console.WriteLine(ConDt);
     Console.WriteLine(ConDt.GetType());
   //Console.WriteLine(folderName.GetType());
   //Console.WriteLine(f.GetType());
}

我尝试使用Convert.toDatetime(),我收到无法创建的错误转换方式我可以这么做吗?

I tried with Convert.toDatetime() and i get error that unable to made the converstion.How can i do so with this?

推荐答案

你应该使用 DateTime.TryParseExact

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

这篇关于将YYYYMMDD字符串日期转换为datetime值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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