Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can convert DateTime.now in C# to yyyy-mm-dd hh:mm:ss.sssssss?

Tags:

c#

datetime

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. 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. 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?

P.s: see the image below with the error message

enter image description here

like image 578
George Panayi Avatar asked Apr 27 '12 10:04

George Panayi


2 Answers

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:

  • Unless you really want the local time, use UtcNow instead of Now. For timestamps, you almost always want UTC.
  • I doubt that you want to use the time separator of the current culture, hence the specification of CultureInfo.InvariantCulture
  • "MM" means months whereas "mm" means minutes
  • "HH" means 24-hour clock whereas "hh" means 12-hour clock
  • "ff..." is used for fractions of a second

See MSDN for more details of custom date and time formatting.

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? 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.

like image 104
Jon Skeet Avatar answered Oct 09 '22 01:10

Jon Skeet


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

like image 38
Dima Avatar answered Oct 09 '22 02:10

Dima