-3

I have an SQL database that I have to store date and time in the records. I am making a project on Visual Studio and I'm using 2 datetime picker controls to prompt for date and time respectively.

I want to know what kind of variable (or class) I should use to store the time and date so that I can store it in the single datetime record in my database.

2 Answers2

1

C# has the DateTime type and TimeSpan for this. TimeSpan is not always the best choice and in many cases its better to just use a DateTime and ignore the date part.

The DateTime Class in C# has a .Date for extracting just the date component and a .Time For the Time part (returning a TimeSpan class)

In SQL you can use DATE and TIME or DATETIME.

You can save a C# DateTime into a DATE,TIME or DATETIME (loosing the part you don't need)

In summary I would suggest using a C# DateTime for the Date and a TimeSpan for the time. And Saving them into SQL as a DATE and a TIME. But you will need to be carefull with TimeSpan as the TimeSpan Is not 100% comparable with SQLs TIME. A TimeSpan in C# can be for more then one day but a time TIME in SQL can only be for one 24 hour period.

Lastly if you have already chosen to use a DATETIME in SQL then why dont you just use a DateTime in C# you can merge the Date And Time thet you get from the UI into one DateTime and just save that in an SQL DATETIME.

Paul Spain
  • 517
  • 3
  • 15
  • After chasing the many iterations of this question around for a bit, I did manage to find the one piece they all seem to lack, which is -- doesn't .NET have anything to offer us, here? (It does, as it turns out...) There is a constructor for the SqlDateTime type that accepts a .NET DateTime as its sole parameter. Why that has not been offered, particularly when the OP often states they are new to .NET -- is a mystery to me https://msdn.microsoft.com/en-us/library/cxsk2s5e(v=vs.110).aspx – jinzai Aug 03 '16 at 21:45
-1

Try this :

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");

Or for more details : Similar StackOverFlow Question with a very good solution or Click here to get all solutions for this problem

Community
  • 1
  • 1
Sandeep Kushwah
  • 590
  • 1
  • 18
  • 35
  • Why down vote?? Perfect way of answering such question. Because it will let questioner know that answer to such questions already exist and how they can reach there. – Sandeep Kushwah Sep 30 '15 at 18:46
  • 1
    Not my downvote, but there is absolutely no information why OP should try code you posted (in addition to be unconventional recommendation). If you want to provide links - it is customary to add summary of each link (or at very least readable reason why one should check it, "here" is not good explanation). – Alexei Levenkov Sep 30 '15 at 19:21
  • Thanks @AlexeiLevenkov I will make an edit to the answer and hope it will be better :) – Sandeep Kushwah Sep 30 '15 at 19:32