[英]How I can convert DateTime.now in C# to yyyy-mm-dd hh:mm:ss.sssssss?
I'm storing in my database using a store procedure the date time stamp using a function called sysdatetime()
and a type of varchar(max)
which stores in the database in this format yyyy-mm-dd hh:mm:ss.sssssss
. 我使用一个名为sysdatetime()
的函数和一个varchar(max)
函数在存储过程中使用存储过程存储日期时间戳,该函数以这种格式存储在数据库中yyyy-mm-dd hh:mm:ss.sssssss
。 When I'm creating a new post its fine but when I'm trying to update the record I have to send a parameter to the store procedure with the current datetime
. 当我正在创建一个新帖子时它很好,但是当我尝试更新记录时,我必须使用当前datetime
向存储过程发送参数。 I have tried this one 我试过这个
DateTime.Now.ToString(yyyy-mm-dd hh:mm:ss.sssssss)
but I'm getting an error. 但我收到了一个错误。 what i have to do? 我该怎么办?
Ps: see the image below with the error message Ps:请参阅下面的图片并显示错误消息
I suspect if you really need the string representation, you actually want: 我怀疑你是否真的需要字符串表示,你真的想要:
string text = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffffff",
CultureInfo.InvariantCulture)
Note that: 注意:
UtcNow
instead of Now
. 除非你真的想要当地时间,否则请使用UtcNow
而不是Now
。 For timestamps, you almost always want UTC. 对于时间戳,您几乎总是想要UTC。 CultureInfo.InvariantCulture
我怀疑你想使用当前文化的时间分隔符,因此是CultureInfo.InvariantCulture
的规范 See MSDN for more details of custom date and time formatting. 有关自定义日期和时间格式的详细信息,请参阅MSDN 。
However, I'd strongly recommend that you try to avoid string conversions wherever possible. 但是,我强烈建议您尽可能避免字符串转换。 Why can't your stored procedure just use the relevant DateTime
type instead of a string representation? 为什么您的存储过程不能使用相关的DateTime
类型而不是字符串表示? Then you can pass the value to the stored procedure as a DateTime
(via a command parameter) and you can get rid of the error-prone string conversion clutter. 然后,您可以将值作为 DateTime
传递给存储过程(通过命令参数),您可以摆脱容易出错的字符串转换混乱。
Use this code: 使用此代码:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff")
See this ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx 请参阅此ref: http : //msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Here a small sample: 这是一个小样本:
DateTime date3 = new DateTime(2008, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with milliseconds: {0:MM/dd/yyy hh:mm:ss.fff}",
date3);
// Displays the following output to the console:
// Date with milliseconds: 01/01/2008 12:30:45.125
Just put the appropriate number of "f"s into your command and you are done 只需在你的命令中输入适当数量的“f”即可完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.