如何将字符串转换为datetime [英] how to convert string to datetime

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

问题描述

我在文件中有以下格式,我想将其转换为DateTime。

我该怎么做?



格式如下:

07/29/2015 08:48:03

解决方案

除了对方之外还有几点积分解决方案......



1.永远不要假设您的数据输入格式正确。

最好使用TryParse [ ^ ]或ParseExact [ ^ ]



2.永远不要假设你的代码只是将在您自己的时区/文化中使用。以某种方式处理其他格式/文化。



例如:(需要使用System.Globalization;

  var  test =   07/29/2015 08:48:03; 

// 所有传入的字符串日期表示将采用美国格式
var culture = CultureInfo.CreateSpecificCulture( en-US);

DateTime dtResult;
if (DateTime.TryParse(test,culture,DateTimeStyles.None, out dtResult))
Console.WriteLine(< span class =code-sdkkeyword> String .Format( 输出日期为:{0} ,dtResult));
else
C onsole.WriteLine( String .Format( 输入字符串是不是{0},culture.Name)中的日期);



因为我的电脑目前是为英国设置的,所以运行时没有错误给出(注意从mm / dd到dd / mm的变化)

输出日期是:2015年7月29日08:48:03 


< blockquote>也许这篇关于CodeProject的文章可以帮助你:

C#日期时间分析器 [ ^ ]



祝你好运!


如果格式正确,您可以将其转换或解析为DateTime。 (可以)使用以下任一代码执行您想要的操作。



  var  date = Convert.ToDateTime(  07/29/2015 08:48:03); 

//

var date = DateTime.Parse( 07/29/2015 08: 48:03);





他们两个都适合你,他们会返回 DateTime 对象。在MSDN上了解有关它们的更多信息。



Convert.ToDateTime() [ ^ ]。

DateTime.Parse() [ ^ ]。


I have the following format in a file and I want to convert that into DateTime.
How can i do that?

The format is of the following:
07/29/2015 08:48:03

解决方案

Couple of points in addition to the other solutions...

1. Never assume that your data input is in the correct format.
It's better to use TryParse[^] or ParseExact[^]

2. Never assume that your code is only going to be used in your own time zone / Culture. Handle other formats/cultures in some way.

For example: (needs using System.Globalization;

var test = "07/29/2015 08:48:03";

//All incoming string date representations will be in US format
var culture = CultureInfo.CreateSpecificCulture("en-US");

DateTime dtResult;
if(DateTime.TryParse(test, culture,DateTimeStyles.None, out dtResult))
    Console.WriteLine(String.Format("Output date is : {0}",dtResult));
else
    Console.WriteLine(String.Format("Input string is not a date in {0}", culture.Name));


Because my PC is currently set up for United Kingdom, this runs without error and gives (Note the change to dd/mm from mm/dd)

Output date is : 29/07/2015 08:48:03


Maybe this article here on CodeProject can help you out:
C# Date Time Parser[^]

Good luck!


You can convert it or parse it to DateTime if it is correct format. (This can be) Use either one of the following codes to do what you want to.

var date = Convert.ToDateTime("07/29/2015 08:48:03");

// OR 

var date = DateTime.Parse("07/29/2015 08:48:03");



Both of them would work for you and they would return a DateTime object. Learn more about them on MSDN.

Convert.ToDateTime() on MSDN[^].
DateTime.Parse() on MSDN[^].


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

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