将字符串转换为特定的DateTime格式

Jos*_*ein 2 c# asp.net

我一直在谷歌搜索一段时间,因为我的生活似乎无法找到解决方案.我认为这很容易,但是花了太长时间才转向stackoverflow.

我需要将包含日期和时间的字符串转换为DateTime变量.我已经将字符串格式化为我想要存储的确切格式但是当我将其转换为DateTime时,它会不断添加我不想要的秒数.我希望它存储为01/01/2010 09:00 AM.这是我到目前为止使用的代码:

DateTime.ParseExact(startTime,"MM/dd/yyyy hh:mmtt", null);
Run Code Online (Sandbox Code Playgroud)

..但它会不断追加秒.请指教.

Dav*_*vid 8

如果它存储为DateTime数据类型,则存储正确,但您的UI 显示错误.无论您如何设置值,DateTime数据类型始终具有秒(毫秒等).问题在于如何将其显示回用户.

您需要在显示时以正确的字符串格式显示所需的日期,如下所示

Label1.Text = startTime.ToString("MM/dd/yyyy hh:mmtt");
Run Code Online (Sandbox Code Playgroud)

编辑 - 添加

要在GridView中对其进行格式化,请参见此处:http: //peterkellner.net/2006/05/24/how-to-set-a-date-format-in-gridview-using-aspnet-20using-htmlencode-property/