如何将字符串转换为日期时间? [英] How to convert string to datetime?

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

问题描述

Hi,

    i am android and Ios developer, i would like to convert string to DateTime

    `string nodeValue = "2013-02-11T14:29:01-05:00";`

    The nodeValue comes from after converting DataSet to XMLDocument

    how can i get the DateTime value as 2/11/2013 2:29:01 PM?

    Help me please...





我尝试过:



i使用Convert.ToDateTime(nodeValue)尝试但它没有返回预期的结果。



What I have tried:

i tried by using Convert.ToDateTime(nodeValue) but it is not returning expected result.

推荐答案

Google发现 DateTime.TryParseExact Method(System) | Microsoft Docs [ ^ ],以微秒为单位。
Google found DateTime.TryParseExact Method (System) | Microsoft Docs[^] in microseconds.


DateTime myDate = DateTime.ParseExact("2013-02-11T14:29:01", "yyyy'-'MM'-'dd'T'HH':'mm':'ss", System.Globalization.CultureInfo.InvariantCulture);





我使用了2013-02-11T14:29:01而不是2013-02-11T14:29:01-05:00及其显示日期时间要求。



谢谢



I have used 2013-02-11T14:29:01 instead of 2013-02-11T14:29:01-05:00 and its showing date time as per the requirement.

Thank You


string nodeValue = "2013-02-11T14:29:01-05:00";
	DateTime result = DateTime.Parse(nodeValue);
	Console.WriteLine(result);





2/11/2013 1:29:01 PM



请注意,如果字符串不是有效日期,则会抛出异常

在这种情况下使用TryParse



2/11/2013 1:29:01 PM

Be aware that if the string is not a valid date an exception will be thrown
in that case use TryParse

ring nodeValue = "2013-13-11T14:29:01-05:00";
	DateTime result;
	 DateTime.TryParse(nodeValue, out result);
	Console.WriteLine(result);





1/0001 12:00:00 AM



1/0001 12:00:00 AM


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

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