将字符串解析为 DateType ASP.NET C# 异常 - 该字符串未被识别为有效的 DateTime [英] Parse string to DateType ASP.NET C# exception - The string was not recognized as a valid DateTime

查看:40
本文介绍了将字符串解析为 DateType ASP.NET C# 异常 - 该字符串未被识别为有效的 DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个这种格式的日期.我的目标是将 7 天添加到此字符串 startdate 并将其作为字符串发布到数据库中.但是,我必须将其转换为日期时间以允许我为其添加天数.我正在从数据库中读取 startdate 但这就是它的样子.

So I have a date which is in this format. My goal is to add 7 days to this string startdate and post it into a database as a string. However, I have to convert it to datetime to allow me to add days to it. I am reading startdate from a database but this is what it looks like.

string startdate = "10-03-2018 03:15PM";

IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm tt", culture); 

//上面那一行出现错误 - 字符串未被识别为有效的 DateTime.

// It is breaking on the above line with the error - The string was not recognized as a valid DateTime.

DateTime endtime2 = starttime2.AddDays(+7);

有人能帮我解决这个问题吗?我是 C# 新手,希望得到任何帮助.

Anyone able to help me solve this issue? I am new to C# and would appreciate any help at all..

谢谢

推荐答案

您实际上指定了错误的格式.您应该指定以下格式:

You have specified wrong format actually. You should be specifying the following format:

"dd-MM-yyyy hh:mmtt"

因为您的日期格式为:

"10-03-2018 03:15PM"

假设我们的第一个数字是日,第二个是月,否则你可以交换它们.

Assuming that the first number us for day and second is for month, otherwise you can swap those.

你可以看到更多关于ParseExact 此处.

You can see more details on the usage of ParseExact here.

这篇关于将字符串解析为 DateType ASP.NET C# 异常 - 该字符串未被识别为有效的 DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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