在c#中将字符串转换为DateTime [英] Convert string to DateTime in c#

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

问题描述

转换以下使用创建的日期的最简单方法是什么

What is the easiest way to convert the following date created using

dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)

转换成一个合适的 DateTime 对象?

into a proper DateTime object?

20090530123001

我尝试过 Convert.ToDateTime(...) 但得到了 FormatException.

I have tried Convert.ToDateTime(...) but got a FormatException.

推荐答案

试试这个:

DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

如果字符串的格式可能不正确(并且您希望避免出现异常),您可以像这样使用 DateTime.TryParseExact 方法:

If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact method like this:

DateTime dateTime;
DateTime.TryParseExact(str, "yyyyMMddHHmmss",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);

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

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