3

I have a webservice method that gets data from sql of the format 2012-11-18 11:21:03 when i save it to C# string it becomes this format: 18.11.2012 11:21:03 How do i change it back to the SQL format 2012-11-18 11:21:03 ?

4 Answers 4

12

Parse it into a dateTime again

DateTime myTime = DateTime.Parse(myString);

and back into a proper to string

myTime.ToString("yyyy-MM-dd HH:mm:ss");

Or just read it into a datetime and cut out the middleman.

Sign up to request clarification or add additional context in comments.

1 Comment

I would use DateTime myTime = DateTime.ParseExact(myString, "yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
2

You can get the universally sortable string format (which looks like the one used by SQL server) by using the format string "u" like this:

var dateTimeString = String.Format("{0:u}", yourDateTime);

1 Comment

Includes a "Z" , for example '2017-02-19 12:21:02Z'
0

Simply run the below code,

var newDateTime = oldDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");

Its just converting it back to the SQL Format DATETIME

1 Comment

Doing that will strip out the time component of 'oldDateTime', and only works if oldDateTIme was already a datetime to begin with
0

Trouble with Dates as strings is they are ambiguous and the formats can vary based on where you are in the world, or even local machine settings. You might assume a date string is yyyy-mm-dd but what if it is actually yyyy-dd-mm? Some dates will appear to work and some will be invalid.

In other words is 2013-02-10 the 10th of February or is it the 2nd of October? If it is just a string you have no way of knowing for sure what was intended.

Your best bet as suggested by #Haedrian is to store in a DateTime C# object, not a string. That way it is never ambiguous and you have access to various date specific functions. If you must store as a string you can convert back to a date as above or use

DateTime.TryParse(datestring, out dateVariable);

which won't throw an exception for an invalid format. Depends if you want exceptions!

Also I would suggest if you must use strings to use a 3 character month in strings, which again eliminates the ambiguity, e.g.

"dd-MMM-yy hh:mm tt"

1 Comment

If it is just a string you have no way of knowing for sure what was intended. If only there were a way to ParseExact ly the format that you wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.