Different date types manipulation - asp.net

I am currently stuck with a database issue where I need to manipulate data using my database inserts. I am currently doing a website with C# ASP.NET on Visual studio 2012 and the database I am using is SQL Management 2008.
Firstly, I currently store my System.Date into a string and store it as a nvarchar datatype in my database. If I would like to perhaps get the latest 10 rows from for example, user= 'x', how should I actually go about doing the SELECT statement to only get the data I specified?
And I currently store information like Date Of Birth using the calander Ajax toolkit so the format the dates are saved in is in month/day/year format. The data is stored into my database as a nvarchar as well. If I want to perhaps calculate the age of user='x' how should I calculate it?

I think Jon's comment about storing the data properly as a datetime is spot on:
Why are you storing it as an nvarchar to start with? It's logically a
date/time, not a string - so store it as a date/time. Get rid of the
string part, and all your formatting problems go away too.
Definitely do that if you can.
If, for some reason, you can't change your database structure, you can use a CAST / CONVERT statement in your ORDER BY clause to get what you want:
SELECT TOP 10 *, CAST(yourDateField AS datetime) AS convertedDate
FROM yourTable
WHERE
user='Some user'
ORDER BY CAST(yourDateField AS datetime) DESC
This assumes that your nvarchar data can be properly converted to a datetime (which it should be if you're using the Ajax Control Toolkit calendar extender).

Related

How to get current date time format in SQlite?

I am using sqlite for local database in mobile and in my database. i want to know that
How to get current date format in SQLITE? I want to get date in the next format: MM/dd/yyyy
To get the current date you can use:
SELECT date('now');
Note: This is NOT a server date, it's the same time you get if you query the date and time directly from your application because SQLITE runs in-process.
It's mostly useful for putting a current time into a table or for some simple calculations if your language's date processing is very poor.
To do the calculations see the SQLITE Documentation
See the docs for formatting too for example:
SELECT strftime('%Y-%m-%d %H:%M:%S', datetime('now'))
According to the SQLite documentation as of this writing (3/30/2020), in the section titled "The DEFAULT clause", it is recommended that a constant value be used instead of a sub-query.
In my experimentation, I also ran into issues with the SQLite CREATE TABLE statement that was generated during model creation by EF Core 3.0 when using SELECT datetime('now'). The SQLite data provider complained of a syntax error when using a SELECT statement within the CREATE table statement. As such, I would recommend using the CURRENT_TIMESTAMP keyword.
for your concrete case, this is what you need:
strftime('%m/%d/%Y',date('now'))

How to add Timestamp value in SQL Server 2005 by using LINQ

My database table have a Timestamp column named as inTime and i am using LINQ for insert, update data in SQL server. Now i want to add the timestamp value in my database but i don't know how to insert?
spaBL.attendance obj = new spaBL.attendance();
obj.FK_employeeId = 1;
obj.inTime =[what to write here??]
inTime is of timestamp type.
Timestamp as in SQL Server Timestamp data type?
;) If I got a cent every time someone did not read the documentation and thought that is a TIME STAMP I would be more rich than bill gates.
Timestamp data time has NO TIME INFORMATION IN IT. It is a running version number, legacy to Sybase SQL Server where SQL Server from Microsoft originated and a totally borked design.
So, no, you CAN NOT SET THAT FIELD, sorry, and it has no usable value except to see whether it changed (then the row was updated).
The documentation is explicitly clear on that, even if some people think reading is maybe a lost art:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx
Is a data type that exposes automatically generated, unique binary
numbers within a database. timestamp is generally used as a mechanism
for version-stamping table rows.
There is no way for you to set it. CHange your LINQ setup to not update this column.
Timestamp values are auto generated by the server on inserts. You should insert rows to the table without supplying a value for the timestamp column. Sql server will then generate the value for the column.
Note the columns of type timestamp does NOT contain values that can be parsed as a DateTime. The idea behind timestamp columns is that they can be used to check if a row has been updated between fetching the row and trying to update the row with new values.
You do not provide values for columns with a Timestamp (Rowversion) data type. SQL Server will provide a value for you automatically (and it won't be a datetime value). Therefore you do not need to be concerned with having Linq To SQL insert a Timestamp value for you. In fact, you cannot do it. SQL Server will do it for you. You can however, retrieve the value of a Timestamp column. I believe the corresponding C# type will be System.Data.Linq.Binary.
How to add Timestamp value in SQL database by using LINQ
hope it helps
You cannot update a timestamp. See here. And indeed, as TomTom indicated, it doesn't contain actual time information.

how to insert date in custom format in sql server table

recently i was working on windows based application in .net, where i have form which has field know as Joining date, which datetimepicker control, whenever user submits the form all the details goes in the sql server table, now the issue is for the date of joining field, sql server inserts its own datetime stamp, as the field is datetime type, but i want to insert the joining date as dd.MM.yyyy, so i used Convert.. like below...
CONVERT(VARCHAR(10), #JoiningDate, 104), i checked this statement in select query with #JoiningDate replaced with GetDate(), it showed me expected results but when i try to insert record, it does not insert record as expected... i am using SP, in sql server 2008, enterprise edition...
can anyone please tell me why this happening...
please reply as soon as possible as it is of utmost important.
Regards
Abbas Electricwala.
your problem may have something to do with the type of your table column. you see, if the column's type is datetime,with your convert operation, you are getting the date value the exact way you want it, but since your column type is datetime, sql will insert a datetime value to it.
you can try and change the column type to varchar(10), and see if it makes a difference.

date format and regional settings

I'm using MS SQL 2000, VS2008, MVC and C#.
I'm trying to insert and update some data using stored procedures.
Some columns are of type datetime.
Regional settings on both server and client are set to Dutch (Belgium)
This means the default date format is dd/mm/yyyy.
When i try to insert or update with a date of eg. 28/03/2009, I get following errors:
Insert:
Error converting data type nvarchar to datetime
Update:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
When I try with a date like 01/03/2009, I get no errors but the date is saved as 03/01/2009, which is the US date format.
This is typical behaviour for problems with regional settings. But both are set to Dutch (Belgium).
Why does it save dates in the US format?
What am i missing here?
Thanks!
Stijn
You should be inserting data into the database using a DateTime object, not a string. Your client-side code should convert the client's date entry to a DateTime object using the client's regional settings, then the DateTime struct should be added to the parameter that is ultimately sent into the database.
The SQL Instance has it's own locale setting, by default "us_english"
Now, this usually happens if you pushing using varchar rather than native datetime to store data values. If your code/tables use datetime columns and you define parameters as datetime then you won't get errors.
i had this problem too, its something to do with the date format for you SQL server,
i solved it by formatting the date string to be inserted like so
DateTime.Now.ToString("MM/dd/yyyy HH:mm")
hope that helps
All above suggestions are correct but I find if you are adding a datetime as a string/varchar the safest way is in the format 'YYYY-MM-DD'
So eg.
Update MyTable
Set MyDate = '2010-03-01'

SQL Server 2005 vs. ASP.net datetime format confusion

I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005.
How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months.
thank you
When you get a DateTime out of the database, it should be in a non-cultured format (like the DateTime object, based on the number of ticks since a certain date). It is only when you are converting that value into a string that you need to be concerned with culture. In those cases, you can use yourDateTimeValue.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) to make sure that the information displays correctly.
I belive that if you use SqlParameters ADO.NET will take care of the rest and you don't have to worry about it. Besides, it's good for defending against SQL Injection attacks too! :)
** Watch out because SQL DateTime columns are non-nullable and their minimum value is 1/1/1753 while .net DateTimes are non-nullable with min values of 1/1/0001. **
If you're pulling data from a real DateTime column, by default it will always be in the same standard format. For saving the data to the column, you might want to specify the SqlDbType.DateTime in your parameter.
i ripped this off of http://bytes.com/forum/thread767920.html :
com.Parameters.Add("#adate", SqlDbType.DateTime).Value = DateTime.Now;
Well, if you keep datetime fields in the DB you shouldn't worry about it.
As long as you keep the dates in app strongly typed (DateTime variables) and send the dates through prepared statements with DBParameter/SqlParameter your DB will take them as is.
If you use strings to hold your dates in code, some casts will ensure you send the right values:
string sqlCmd = #"SELECT *
FROM MyTable
WHERE MyDateField = CONVERT(datetime, '{0}', 101)";
// assuming myDateString is a string with a date in the local format
sqlCmd = string.Format(sqlCmd,
Convert.ToDateTime(myDateString).ToString("yyyyMMdd"));
(the code is ugly, but hopefully it gets the point across)
As others have mentioned, you should be OK as far as storing datetimes culturally. What I would recommend is that you store all of your times as standard UTC time. In SQL Server 2005 and older there is no way to store time zone information, but if everything is stored in universal time, you should be OK because the time can be converted to the local time later on.
SQL Server 2008 does have some datatypes that are aware of time zones, and if you're using .NET 3.5 there are tools to assist with time zone handling/conversions.
Definitely keep times in universal format. This will make a world of a difference if you have to work in multiple time zones.

Resources