简体   繁体   中英

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

Ps: see the image below with the error message

在此输入图像描述

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM