将DateTime字符串转换为Datetime

编程入门 行业动态 更新时间:2024-10-27 09:36:16
本文介绍了将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.Parse或System.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

本文发布于:2023-11-22 15:23:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   DateTime   Datetime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!