I need to pass a string parameter to a stored procedure that represents a date but is only 10 characters long. I cannot alter the stored procedure to change the variable type or length. My only option is to use C# to ensure that the parameter is suitable.
To do this I want to convert a DateTime object to a string and remove the time. I tried using the .Date method on the DateTime object but this merely converted the time to midnight. This was ok on my local machine which represented midnight by a series of zeros but on the machine I was deploying to my code midnight was represented by 12am. This causes the stored procedure to throw an exception.
I also tried forming a substring by taking the first 10 characters after converting the DateTime object to a string. However, this gave inconsistent results due to the fact that some days and months are single digits whereas others are double digit.
For example:
12/12/2010 gets converted to "12/12/2010"
but
01/01/1900 gets converted to "1/1/1900 1" (the '1' coming from the beginning of 12:00:000AM)
You can use
string date = dt.ToShortDateString();
or (synonymous)
string date = dt.ToString("d");
or
string date = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
The last way ensures the format even if your current culture's date-format is different.
There are many ways to do this one to try is:
var myDateTime = DateTime.Now;
var parameter = myDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
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.