How to string year to datetime in sql server - c#

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

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
}

As a note, if you only care about the year then I would highly suggest that the database field should be an Int instead of a DateTime.
The minimum sql datetime value is 1/1/1753 for a number of reasons that you can certainly look up. However, the point is that a regular DateTime field is storing way more information than you care about.
So if you deal with publications older than 1753 you're going to run into an architectural issue. And, if somehow you didn't, you'd certainly run into issues deciding if a publication was 280 years old or 279 or 281...

You could use a drop down list with the available years? If there are only three possible publication years, then this would make more sense as an input control. Grab the year and pad the DateTime month and day values with "1" each.

Related

I have the number of days (stored in SQL db as 37867) since 1900 and want to convert it to a date like "Sep-5-2003

I have a number retrieved from SQL = 37867 and need to convert it to the date it represents which is 2003-09-05.
The number 37867 represents the number of days since 1900 and the answer should be 2003-09-05 but how to calculate this in C#?
This is the SQL function that does it: "SELECT CONVERT(datetime,37867)" but how can I do it in C# so I can update that int and make it a string literal and replace that int with that string?
I am guessing that this is how the struct for Windows stores the DateTime stamp.
If I spend enough time I am pretty sure I can figure it out, but it will take more time than I really want to spend and if someone else already has...why re-invent the wheel?
This community generally prefers that you make an attempt, if we see what you were attempting to do it's generally easier to help then writing something from scratch.
Having said that:
// Create new DateTime, January 1st 1900
var dt = new DateTime(1900, 1, 1);
// Add 37867 days to that DateTime
dt = dt.AddDays(37867);
// Call ToString()
var s = dt.ToString();

Adding months to a DateTime variable

I have a datetime variable with value 12-02-2019 (12th Feb 2019) - this is what i want. But in my code, it is in MM-dd-yyyy format. It saves to db in MM-dd-yyyy format (2nd Dec 2019). When i return it from Datebase, it will be like 02-12-2019 (2nd Dec 2019).
int salesid = (int)dr["SalesID"]; // dr is the datarow
DateTime salesdate = (DateTime)dr["SalesDate"]; // 02-12-2019 (2nd Dec)
And I want to add 4 months to 12-02-2019 (12th Feb). But the runtime adds 4 months to 02-12-2019 (2nd dec) and i am getting 02-04-2020 !!!
DateTime servicedate = salesdate.AddMonths(4); // 2020-12-02
This is wrong. I want to specify the salesdate as 12th Feb 2019 and ii should get 12th June 2019 after adding 4 months to the salesdate.
How this is possible in c# ?
When you save to the DB, make sure you are specify a more verbose format that the DB cannot confuse. For example, if you supply write to the database with myDateTime.Format("dd MMM yyyy"); then it will not confuse the months and days around.
This will make sure that the format in your code, and in you database, all stay aligned.
The problem is in your INSERT statement. While you should be passing the DateTime as-is to your database API, instead of using strings, if you want a simple fix, instead of calling ToString() on your CurrentSaleItem.SaleDate, use a different overload that lets you specify the culture and/or format explicitly, like ToString(string, IFormatProvider)

C# set April 1st as start of year

I'm currently working on an app to add data to a SQL table.
One of the fields in the table is for financial month as YYYYMM (e.g. 201805 for August 2018). I need to set this automatically when the row is added as we can't rely on the users to input the correct format.
Is there any way to set DateTime to start the year on 1st April (first day of financial year), or am I going to have to code my way around the issue.
Thanks for all the answers, they did help me solve the problem.
I eventually went with a really simple solution that I probably should have thought of in the first place.
string period = DateTime.Now.AddMonths(-3).ToString("yyyyMM");
What you want is a varchar (or nvarchar) column, with a default that looks something like:
(format(dateadd(month,(-4),getdate()),''yyyyMM'',''en-US''))
But, it appears that SQL Server doesn't like having a default with three functions nested inside each other (two, it seems ok with, but it burps on three). Instead, you can have a Date type column with a default of:
(dateadd(month,(-4),getdate()))
That seems to work, but it's a date 4 months ago. Then just format it correctly whenever you display it.
You could use the following piece of code to get the start of your desired financial year.
var year = DateTime.Now.Year;
DateTime firstDay;
if(DateTime.Now.Month <= 4)
firstDay = new DateTime(year-1, 4, 1);
else
firstDay = new DateTime(year, 4, 1);
There doesn't seem to be a way to do this automatically, but it looks simple enough.

.NET DateTime to SqlDateTime Conversion

While converting .NET DateTime (when is default(DateTime)) to SqlDateTime should I always check if the .NET date is between SqlDateTime.MinValue and SqlDateTime.MaxValue [or] Is there a good way to do this.
Is it possible that the date could actually be outside that range? Does it come from user input? If the answer to either of these questions is yes, then you should always check - otherwise you're leaving your application prone to error.
You can format your date for inclusion in an SQL statement rather easily:
var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.
SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)
Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.
Also please remember resolutions [quantum of time] are different.
http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx
SQL one is 3.33 ms and .net one is 100 ns.
on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...
when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.
EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());
also Fakrudeen's link brought me further... thank you.
-To compare only the date part, you can do:
var result = db.query($"SELECT * FROM table WHERE date >= '{fromDate.ToString("yyyy-MM-dd")}' and date <= '{toDate.ToString("yyyy-MM-dd"}'");
var sqlCommand = new SqlCommand("SELECT * FROM mytable WHERE start_time >= #StartTime");
sqlCommand.Parameters.Add("#StartTime", SqlDbType.DateTime);
sqlCommand.Parameters("#StartTime").Value = MyDateObj;

Building a Datetime Object for SQL database insert

I'm working on a small web form that requires the user to input (among other things), the scheduled backup time of whatever server they're adding to the system. The problem is, I'm struggling to find out the best way to take the user input and build a DateTime object (which is what the database requires).
I only really care about the Day of Week, Time of Day (12 or 24 hour clock).
I thought about just creating an empty DateTime object and then just adding my input values from the user, but you can only get, not set, the day of week, time of day, etc.
I've been looking at the Calender asp control, which would work for the day of the week selection, but I can't seem to find any support of time of day.
Thanks.
I don't think you want to use a DateTime for a recurring event such as a backup. A DateTime is useful for storing a particular date and time, but not a "template" for a recurring event. Instead I'd use separate columns to store the day of week value (0-6) and time of date (minutes after midnight) for the event.
If you going to use datepicker here is one great sample for adding JQuery date picker using C#. That helped me including in my project evrn if I did know anything abaut JQuery and java sripts at all.
DateTime is a immutable value type. You cannot set anything on it.
Assumed that you stick with DateTime on the DB and you don't want to use a DateTimePicker control.
You have to specify how the day of week and the time should be represented in the DateTime. You can start with DateTime.MinValue, the 1.1.0001, 12:00 at midnight, and add the day of week and the time. unfortunately, a regular DateTime field in a SqlServer 2005 is not able to store this date. So lets move it to the year 2000. The 1.1.2000 was a Saturday. You could calculate the DateTime like this:
int dayOfWeek; // 0 = mon, 6 = son
DateTime time;
DateTime scheduleTime = new DateTime(2000, 1, (dayOfWeek + 2) % 6 + 1)
+ time.TimeOfDay;
But honestly, I wouldn't do it. It smells. I just answered your question. Listen to tvanfosson. He said everything that needs to be said.

Categories

Resources