Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to string year to datetime in sql server

I have a textbox without calendar control and we will call it as publication year(we use diff name in our project). The publication year is 1999, 2001 or 1860.

My step goes like this

I have datetime in my database.(unchangable)

I am using C# and sql server 2005.

string date = textBox1.text;
Datetime dt = Convert.ToDateTime(date);

I pass dt to my database using dynamic sql

to trick the code, I added a prefix 1/1/ before my entered date like 1/1/2010 , it worked well

Now my TL asked me not to do like that.... I am ??? . Please help

like image 249
Karthik Ratnam Avatar asked Apr 30 '26 19:04

Karthik Ratnam


1 Answers

It sounds like you should really:

  • Parse the text as an integer
  • Create a new DateTime with that year, and January 1st as the day/month.

For example:

int year;
if (int.TryParse(textBox1.Text, out year))
{
    DateTime dt = new DateTime(year, 1, 1);
}
else
{
    // Handle input
}
like image 127
Jon Skeet Avatar answered May 03 '26 08:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!