如何在c#中为时间戳数据类型分配默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/672961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:48:59  来源:igfitidea点击:

How to assign default value to timestamp datatype in c#?

c#.netsqllinqlinq-to-sql

提问by Vikas

I want to assign default value to timestamp datatype in c#?

我想在 c# 中为时间戳数据类型分配默认值?

I have an object of table in c#.

我在 C# 中有一个 table 对象。

采纳答案by andleer

A SQL TimeStamp is based on insert / update order on your sql server. There is no way to assign it from within C#. I doubt SQL will even allow you to update a column of type TimeStamp.

SQL 时间戳基于 sql 服务器上的插入/更新顺序。无法从 C# 中分配它。我怀疑 SQL 甚至会允许您更新 TimeStamp 类型的列。

TimeStamp is a binary sequence. (8 bytes I believe.) There is no correlation to a DateTime. Nothing to display for the user on a page.

时间戳是一个二进制序列。(我相信 8 个字节。)与 DateTime 没有相关性。页面上没有要向用户显示的内容。

If you want to show the user when a record was last modified or first created, you will have to maintain separate fields of type DateTime and update the values in either your application or within sql using sprocs or triggers.

如果您想向用户显示上次修改或首次创建记录的时间,则必须维护 DateTime 类型的单独字段,并使用 sproc 或触发器更新应用程序或 sql 中的值。

回答by ripper234

For a DateTime object, just use

对于 DateTime 对象,只需使用

var d = new DateTime();

回答by RvdK

DateTime d = new DateTime(2009,3,23);

日期时间 d = 新日期时间(2009,3,23);

msdn

msdn

回答by Jim Mischel

According to the documentation, the Transact-SQL timestampdata type is just an incrementing number and does not preserve a date or a time. You can't convert that to a meaningful DateTimevalue.

根据文档,Transact-SQL时间戳数据类型只是一个递增的数字,不保留日期或时间。您无法将其转换为有意义的DateTime值。

The documentation says that it's an 8-byte value. So, if it's stored in a System.Data.Linq.Binary, you could convert it to a longwith this code:

文档说它是一个 8 字节的值。因此,如果它存储在 a 中System.Data.Linq.Binary,您可以long使用以下代码将其转换为 a :

System.Data.Linq.Binary timestampValue;
// Somehow get a reference to the SQL timestamp you're interested in

// Use BitConverter to convert the 8 bytes to a long
long timestampLong = BitConverter.ToInt64(timestampValue.ToArray(), 0);

You could try to convert that value to a DateTimeby calling the constructor that takes a ticksvalue, but the results would be meaningless. You might also encounter an exception if the ticksvalue is out of range.

您可以尝试DateTime通过调用带ticks值的构造函数将该值转换为 a ,但结果将毫无意义。如果ticks值超出范围,您也可能会遇到异常。