将日期时间转换为字符串并返回到时间 [英] Convert date time to string and back to date time

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

问题描述

我在将字符串转换为DateTime时遇到麻烦。这是我有的首先将当前日期转换为字符串(这将是文件夹名称)。

I'm having a troubles with converting strings to DateTime. Here is what I have. First I convert current date to string (this will be folder name).

string dateString = string.Format("{0:yyyy-MM-dd_HH-mm-ss}", DateTime.Now);

输出如下


2013-05-16_09-32-47

2013-05-16_09-32-47

然后我创建一个文件夹。在程序执行期间,我得到这个文件夹,我需要将其名称转换回DateTime。尝试让它像这样

Then I create a folder. During program execution I get this folder and I need to convert it's name back to DateTime. Try to make it like this

DateTime directoreDate = DateTime.ParseExact(directory.Name, "0:yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);

但它会抛出FormatException。任何人都可以告诉我为什么会发生这种情况。

But it throws FormatException. Can anybody tell me why this happening.

推荐答案

您正在使用与用于格式化原始 DateTime 。这不需要 ParseExact - 从中​​删除 0:

You are using the same composite format string that you used to format the original DateTime. This is not needed for ParseExact - drop the 0: from it:

DateTime directoreDate = DateTime.ParseExact(directory.Name, 
                                             "yyyy-MM-dd_HH-mm-ss", 
                                             CultureInfo.InvariantCulture);

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

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