将DateTime字符串转换为Datetime [英] Convert DateTime String to Datetime

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

问题描述

我有一个来自外部的价值

我正在获取字符串值(07/03/2011 12:00:00 AM),我想转换为DateTime并更新数据库.
目前,我正在尝试以下方法,但还是不行...

选项1:

Hi i have a value coming from external

Am getting string value (07/03/2011 12:00:00 AM ) and i want to convert to DateTime and update the Database.
At present am trying below methods but still no go...

Option 1:

DateTime  myDateTime = System.Convert.ToDateTime(item.StartDate);


选项2:


Option 2:

string strDateTime = sampledate; //(when i use this "it shows Cannot implicitly convert type system.DateTime ? to String)
DateTime myDateTime = DateTime.Parse(strDateTime );


请有人指导我转换的正确方法是什么


更新1:

下面的代码正在工作


Please some one guide me what is the right way to convert


Update 1:

The below code is working

DateTime strDateTime = System.Convert.ToDateTime(item.StartDate); 
string conv=System.Convert.ToString (strDateTime); 
DateTime dateToSave; 
bool canParse = DateTime.TryParse(conv, out dateToSave); 

if (canParse)
 {
 Console.WriteLine("Testok");
 } 
else
 {
 Console.WriteLine("Fail");
 }

推荐答案

使用重载的方法之一System.DateTime.ParseSystem.DateTime.ParseExact.

-SA
Use one of the overloaded methods System.DateTime.Parse or System.DateTime.ParseExact.

—SA


使用DateTime.TryParse方法.

方法是这样的:

Use DateTime.TryParse method.

This is how it is done:

DateTime dateTime;

DateTime.TryParse(strDateTime, out dateTime);



最酷的部分是TryParse如果解析成功将返回True,如果解析失败则返回False.您可以在if条件下使用该语句.


更新1:



The coolest part is TryParse will return True if the parsing is successful and return False if the parsing fail. You can either use the statement in a if condition.


Update 1:

shan1395写道:
shan1395 wrote:

DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);

DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);



此代码是将字符串转换为DateTime的方法之一.如果您使用Convert.ToDateTime
,则不需要使用TryParse.
如果字符串为空,则Convert.ToDateTime将失败并引发异常.但是TryParse不会引发异常.

解决方案1:



This code is one of the ways to convert string to DateTime. It is not required to use TryParse if you use Convert.ToDateTime

Convert.ToDateTime will fail and throw exception if the string is empty. But TryParse will not throw exception.

Solution 1:

DateTime dateTime = System.Convert.ToDateTime(item.StartDate);





解决方案2:



or

Solution 2:

DateTime dateTime;

DateTime.TryParse(item.StartDate, out dateTime);



如果有帮助,请将其标记为答案



Mark it as answer if it is helpful


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

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