C# 将字符串转换为 12 小时格式的日期时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16165703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a string to datetime format with 12 hour format
提问by Khushbu
I am having a field type DateTime in SQL server database. I am developing a webservice to fetch date and time.
我在 SQL 服务器数据库中有一个字段类型 DateTime。我正在开发一个网络服务来获取日期和时间。
The date is stored in this format 4/14/2013 10:10:01 PM in database.
日期以这种格式存储在数据库中 4/14/2013 10:10:01 PM。
Now, I have a webmethod as below:
现在,我有一个 webmethod 如下:
public string GetdataJson(string lastdate)
{
DateTime myDateTime = DateTime.Parse(lastdate);
string getvalue = "select * from tblfameface where last_updated >='" + myDateTime + "'";
con1 = new SqlConnection(conString1);
con1.Open();
SqlCommand cmd = new SqlCommand(getvalue, con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
da.Fill(dt1);
string jsonString = JsonConvert.SerializeObject(dt1);
String finalString = "{\"Records\":";
finalString += jsonString;
finalString += "}";
return finalString;
}
But this code is giving me an error of String was not recognized as a valid DateTime. how can I convert string into datetime format like 4/14/2013 10:10:01 PM?? help!
但是这段代码给了我一个错误,字符串未被识别为有效的日期时间。如何将字符串转换为日期时间格式,如 4/14/2013 10:10:01 PM?帮助!
采纳答案by jordanhill123
Try this:
尝试这个:
string getvalue = "select * from tblfameface where
last_updated >= Convert(DateTime, '" + myDateTime + "')";
or this depending on you SQL data type on column last_updated
或者这取决于您在 last_updated 列上的 SQL 数据类型
string getvalue = "select * from tblfameface where
last_updated >= Convert(DateTime2(7), '" + myDateTime + "')";
回答by Hossein Narimani Rad
In your format string use ttfor PM/AMpart. Here is the code:
在您的格式字符串中tt用于PM/AM部分。这是代码:
DateTime dateTime =
DateTime.ParseExact("4/14/2013 10:10:01 PM",
"M/dd/yyyy hh:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture);
This should also works:
这也应该有效:
DateTime result = DateTime.Parse("04/14/2013 10:10:01 PM");
Are you sure you are getting the correct string?
你确定你得到了正确的字符串?
回答by Mandeep Singh
Use this Code
使用此代码
DateTime.ParseExact(yourString, "MM/dd/yyyy hh:mm:ss tt");
回答by Ramesh Rajendran
You want 12-hour clock use small hh , You want the 24-hour clock use capital HH
你要 12 小时制用小号 hh ,你要 24 小时制用大写 HH
DateTime formatted =Covert.ToDateTime( lastdate.ToString("dd/MM/yyyy hh:mm:ss.fff",
CultureInfo.InvariantCulture));
If you want to use the 12-hour clock, use tt in the format string to produce the AM/PM designator.
如果要使用 12 小时制,请在格式字符串中使用 tt 来生成 AM/PM 指示符。
回答by PRASHANT
Replace query line by
替换查询行
string getvalue = "select * from tblfameface where CAST(last_updated AS
DATETIME)>='" + myDateTime.ToString("dd/MM/yyyy hh:mm:ss tt") + "'";

