我有以下字符串存储在数据表中的列与VARCHAR或字符串数据类型 “2013年4月29日下午九点零零分00秒”C#字符串日期时间在c#
现在我想这个字符串转换成datetime
或 让我更清楚 我只是想从这个字符串中提取时间部分“2013年4月29日9:00:00” 并将其存储在数据库中。 请帮帮我。 在此先感谢
我有以下字符串存储在数据表中的列与VARCHAR或字符串数据类型 “2013年4月29日下午九点零零分00秒”C#字符串日期时间在c#
现在我想这个字符串转换成datetime
或 让我更清楚 我只是想从这个字符串中提取时间部分“2013年4月29日9:00:00” 并将其存储在数据库中。 请帮帮我。 在此先感谢
好的,这是一个相当简单的操作,您可以使用DateTime date = DateTime.Parse(dbString)
,然后使用date.ToString("hh:mm tt")
为了得到时间和上午/下午。其形式为 “下午9点”
'HH' 代表小时01到12,
'毫米' 代表分钟00〜59,
'TT' 表示AM/PM
您还可以使用date.ToString("h:mm tt")
获取表格“9:00 PM”。
DateTime yourDateTime = DateTime.ParseExact(dateString, "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
试试这个:
string myDateTimeString = "4/29/2013 9:00:00 PM";
DateTime myDateTime = DateTime.Parse(myDateTimeString);
string myTimeString = myDateTime.Date.ToString("hh:mm tt");
希望这有助于!
// String to DateTime
String MyString;
MyString = "4/29/2013 9:00:00 PM";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "M/dd/yyyy hh:mm:ss tt",
null);
这应该适合你。字符串的SQL
+1因为这个答案不会使UASA根据数据库本地或代码访问它的假设。 – 2013-04-29 09:56:51
几乎是正确的 - 你真的应该有'MM/dd/yyyy hh:mm:ss tt'',因为月份可能是两位数字。 – 2013-04-29 09:58:20
+1给格式,因为多次日期解析是一个痛苦的屁股。如果我们事先知道格式,最好给它。在写作部分也必须小心。 – sarat 2013-04-29 09:58:54
时间部分:
select DATEPART(HOUR , cast('4/29/2013 9:00:00 PM' as datetime)) as hr
, DATEPART(MINUTE , cast('4/29/2013 9:00:00 PM' as datetime)) as minute
, DATEPART(SECOND , cast('4/29/2013 9:00:00 PM' as datetime)) as sec
或者试试这个分机:
public static class Ext
{
public static string AsLocaleDateString(this DateTime dt)
{
var format = Thread.CurrentThread.CurrentUICulture.DateTimeFormat;
return dt.ToString(format.ShortDatePattern);
}
public static DateTime? AsLocaleDate(this string str)
{
if (str.IsNullEmpty())
{
return null;
}
var format = Thread.CurrentThread.CurrentUICulture.DateTimeFormat;
return DateTime.ParseExact(str, format.ShortDatePattern, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
}
http://msdn.microsoft.com/en-us/library/vstudio/cc165448.aspx或http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For – bema 2013-04-29 09:50:16
你有没有签出MSDN文档? http://msdn.microsoft.com/en-us/library/cc165448.aspx – HuorSwords 2013-04-29 09:50:17
你想把它存储回来作为一个字符串,或作为一个不同的字符串类型? – 2013-04-29 09:50:22