SQL Server Timestamp using with C# - c#

In my database I have used Timestamp in each table to see when data was inserted.
It stores data in byte[] of 8 byte.
Now I want to read that time using C#.
How can I get DateTime object from Timestamp which is byte[]?

SQL Server's TIMESTAMP datatype has nothing to do with a date and time!
It's just a binary representation of a consecutive number - it's only good for making sure a row hasn't change since it's been read.
In never versions of SQL Server, it's being called RowVersion - since that's really what it is. See the MSDN docs on ROWVERSION:
Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism
for version-stamping table rows. The
rowversion data type is just an incrementing number and does not
preserve a date or a time. To record a date or time, use a datetime2
data type.
So you cannot convert a SQL Server TIMESTAMP to a date/time - it's just not a date/time.
But if you're saying timestamp but really you mean a DATETIME column - then you can use any of those valid date formats described in the CAST and CONVERT topic in the MSDN help. Those are defined and supported "out of the box" by SQL Server. Anything else is not supported, e.g. you have to do a lot of manual casting and concatenating (not recommended).
The format you're looking for looks a bit like the ODBC canonical (style = 121):
DECLARE #today DATETIME = SYSDATETIME()
SELECT CONVERT(VARCHAR(50), #today, 121)
gives:
2011-11-14 10:29:00.470
SQL Server 2012 will finally have a FORMAT function to do custom formatting......

Related

problem on formatting DateTime in parametised query [duplicate]

I am using C# and MySql. I have a requirement where I need to save DateTime.MaxValue to one of the column.
ADO.NET code gives me below value for DateTime.MaxValue
12/31/9999 11:59:59 PM
When I save this in mysql, I see that the value for that datetime(3) column is saved as:
0000-00-00 00:00:00.000
Sample ADO.NET Code
DateTime time = DateTime.MaxValue;
sqlCommand.Parameters.AddWithValue("Expires", time);
sqlCommand.ExecuteNonQuery();
DataType of the column is datetime(3)
I still cannot figure it out why DateTime.MaxValue is saved as 0000-00-00 00:00:00.000
Any thoughts around this?
A DATETIME column can store values up to '9999-12-31 23:59:59'. DateTime.MaxValue is actually 9999-12-31 23:59:59.9999999. When you try to insert it, the fractional seconds overflow the maximum size of the field.
Normally (in STRICT mode), MySQL Server would issue a datetime field overflow error. But if you're running your server in ANSI mode, the overflow is silently converted to the "invalid" date time value 0000-00-00.
One way to fix this problem is to use STRICT mode in your MySQL Server.
Another way is to specify the column type as DATETIME(6), which allows the fractional seconds to be stored.
A third way is to truncate the fractional seconds from your DateTime objects in C# before inserting them in the database.
Maybe some trigger prevents from saving such a high date to your column?
Have u tried inserting that date from SQL query ?
I did some tests in Oracle DB, and all went smoothly.
It shouldnt be different in mysql ...

Datetime milliseconds getting wiped in C# SQLite connection [duplicate]

I have a SQLite database where I store the dates as ticks. I am not using the default ISO8601 format. Let's say I have a table defined as follows:
CREATE TABLE TestDate (LastModifiedTime DATETIME)
Using SQL, I wish to insert the current date and time. If I execute any of the below statements, I end up getting the date and time stored as a string and not in ticks.
INSERT INTO TestDate (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
INSERT INTO TestDate (LastModifiedTime) VALUES(DateTime('now'))
I have looked at the SQLite documenation, but I do not seem to find any option to obtain the current timestamp in ticks.
I can of course define a parameter in C# and store the value as a System.DateTime. This does result in the datetime getting stored to the database in ticks.
What I would like to do is be able to insert and update the current timestamp directly from within the SQL statement. How would I do this?
Edit:
The reason I want the data stored as ticks in the database, is that the dates are stored in the same format as stored by the ADO.Net data provider, and so that when the data is also queried using the ADO.Net provider it is correctly retrieved as a System.DataTime .Net type.
This particular oddity of SQLite caused me much anguish.
Easy way - store and retrieve as regular timestamp
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (datetime('now'));
select datetime(LastModifiedTime), strftime('%s.%f', LastModifiedTime) from TestDate;
Output: 2011-05-10 21:34:46|1305063286.46.000
Painful way - store and retrieve as a UNIX timestamp
You can use strftime to retrieve the value in ticks. Additionally, to store a UNIX timestamp (roughly equivalent to ticks), you can can surround the number of seconds in single-quotes.
insert into TestDate (LastModifiedTime) values ('1305061354');
SQLite will store this internally as some other value that is not a UNIX timestamp. On retrieval, you need to explicitly tell SQLite to retrieve it as a UNIX timestamp.
select datetime(LastModifiedTime, 'unixepoch') FROM TestDate;
To store the current date and time, use strftime('%s', 'now').
insert into TestDate (LastModifiedTime) VALUES (strftime('%s', 'now'));
Full example:
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (strftime('%s', 'now'));
select datetime(LastModifiedTime, 'unixepoch') from TestDate;
When executed by sqlite3, this script with print:
2011-05-10 21:02:34 (or your current time)
After further study of the SQLite documentation and other information found on date number conversions, I have come up with the following formula, which appears to produce correct results:
INSERT INTO TestDate(LastModifiedTime)
VALUES(CAST((((JulianDay('now', 'localtime') - 2440587.5)*86400.0) + 62135596800) * 10000000 AS BIGINT))
Seems like a painful way to produce something that I would expect to be available as a built-in datetime format, especially that the database supports the storing of datetime values in ticks. Hopefully, this becomes useful for others too.
Update:
The above formula is not perfect when it comes to daylight savings. See section Caveats And Bugs in SQLite docs regarding local time calculation.
The following will return the number of milliseconds since the UNIX Epoch:
SELECT (strftime('%s', 'now') - strftime('%S', 'now') + strftime('%f', 'now')) * 1000 AS ticks
It works by grabbing the number of seconds since the Unix Epoch (%s), subtracting the number of seconds in the current time (%S), adding the number of seconds with decimal places (%f), and multiplying the result by 1000 to convert from seconds to milliseconds.
The subtraction and addition are to add precision to the value without skewing the result. As stated in the SQLite Documentation, all uses of 'now' within the same step will return the same value.

how print timestamp in ASP.net

I have in SQl Server table with col timestamp.
Now i use Entity Framework 6, and get in model field byte[].
Now what I should do to save current date to this field, and what i should do to print in view this date like(dd/mm/yyyy hh/mm/ss)
I find this:
How to convert byte array (SQL-server Timestamp) to DateTime (C#)?
and I felt that I should not use tiemstamp. What is a correct way to solved it?
The timestamp data type in SQL Server is a misnomer. It is not related to date/time at all so it cannot be converted to a .NET DateTime. The SQL Server timestamp data type is actually a binary value that changes every time the row is updated, intended to be used for optimistic concurrency checking. The use of the timestamp data type name is deprecated in favor of the alias rowversion in later SQL Server versions.
You need to use SQL Server data type datetime, datetime2, datetimeoffset, or time to store temporal values in SQL Server.

.Net DateTime cannot be saved to SQL Server DATETIME because of precision

I have a property on an class that is of the .Net type DateTime. It is attempting to save into a table in SQL Server 2008 with a type of DATETIME. I am receiving a Database Error when I attempt to save a new record to the table from my .Net service.
When I look at SQL Server Profiler and see the call to the Stored Procedure that saves to the table, the property is a string: '2014-09-04 23:08:18.0500000'. When I truncate this string to just milliseconds the Stored Procedure call succeeds. The conversion of my .Net DateTime property to this string all happens under the hood and I have no control over that.
I do not need the full precision that I am seeing in the string, but it is important to keep milliseconds. I would rather not change my table column to a data type of DATETIME2. How can I remove the extra precision from the .Net DateTime property?
DateTime dateTime;
dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
Please have #Tanner reply and mark that as an answer if correct as I believe he is correct in his comment above. Be careful to check for NULL on DateTime as you cannot convert to formated string if no data exists.
Below explains the range of DATETIME field in SQL Server.
http://msdn.microsoft.com/en-us/library/ms187819.aspx

Is is possible to change the date format of the LastLoginDate in the aspnet_membership table?

In the current project I'm working the initial developer had used ASP.NET Membership to handle the user login validation. As such the LastLoginDate and the LastActivityDate in the aspnet_Membership table are save in UTC format.
Is there anyway to save it in the local time format? Or does anyone know which stored procedure could be modified to compensate for the time difference (by using the DATEADD() method)?
I would caution against changing the data from UTC to local time.
SqlMembershipProvider returns MembershipUser.LastLoginDate and other similar properties in local time: i.e. it converts the database value from UTC to local.
So if you're accessing this data via the Membership API, you don't need to do this.
If you're accessing the data in the database directly, and you really, really want SQL Server to return it in local time, why not just convert it when you're reading from the database.
For example, you could create a VIEW on the aspnet_Membership table something like:
SELECT
...
LastLoginDate + GETDATE() - GETUTCDATE() AS LastLoginDateLocal
...
FROM aspnet_Membership
Note that by doing the conversion in SQL Server, you'll be getting the local time of the SQL Server, which may not be the same as the local time on the machine hosting your application.
UPDATE
From comments:
I want to know why #Leo approach didn't work.
#Leo suggested modifying the aspnet_Membership_UpdateUserInfo SP; you need to modify all SPs that update the columns you're interested in. For example, LastLoginDate is also updated by aspnet_Membership_UpdateUser.
Also, if you follow this approach, the time returned in MembershipUser.LastLoginDate property will be incorrect, since the SqlMembershipProvider code assumes the database value is in UTC. To correct this problem, you would need to modify all the Membership SPs that SELECT this column, to convert back to UTC. E.g. aspnet_Membership_GetAllUsers, aspnet_Membership_FindUsersByEmail, aspnet_Membership_FindUsersByName, ...
Note also that converting between UTC and local in SQL Server as above will sometimes give incorrect values (+/- 1h) due to DST (e.g. the difference GETDATE() - GETUTCDATE() is calculated during a period when DST is in operation, but the user last logged in before DST started).
Another reason why it's better to leave the database value in UTC, and do any conversion in your application.
aspnet_Membership_UpdateUserInfo is the Sp which update the LastLoginDate. You can modify this SP and cast the data format according to your requirement.

Categories

Resources