Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
960 views
in Technique[技术] by (71.8m points)

c# - How to persist DateTime Kind while storing a datetime object into a data table?

I’m facing an issue with storing the DateTime object into a datatable, it looses the Kind information set into it.For example if the DateTime.Kind is UTC, once I assign it to the datarow value it changes the Kind to Unspecified.Please find the code below.

public class LocalTimeToUtcConverter
    {
        public DateTime Convert(DateTime localDate)
        {
            var utcOffset = TimeZoneInfo.Local.GetUtcOffset(localDate);

            var utc = localDate.ToUniversalTime();

            return utc + utcOffset;
        }
    }

 [Test]
        public void Should_set_datetime_column_kind_to_utc()
        {            
            var localDate = new DateTime(2010, 11, 01, 00, 00, 00);
            Assert.That(localDate.Kind == DateTimeKind.Unspecified);
            var converter = new LocalTimeToUtcConverter();
            DateTime date = converter.Convert(localDate);
            Assert.That(localDate.Kind == DateTimeKind.Utc);
            var data = CreateTable(date);
            //Failes-Why????
            Assert.That(((DateTime)data.Rows[0].ItemArray[0]).Kind ==   DateTimeKind.Utc);
        }

        private DataTable CreateTable(DateTime date)
        {            
            DataTable table = new DataTable();            
            table.Columns.Add(new DataColumn("Date1", typeof(DateTime)));

            for (int i = 0; i < 10; i++)
            {
                var newRow = table.NewRow();
                newRow[0] = date;
                table.Rows.Add(newRow);
            }

            return table;
        }

Please can you tell me a workaround for this?

Thanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

table.Columns.Add(new DataColumn("Date1", typeof(DateTime)));

Use the DataColumn.DateTimeMode property:

var col = new DataColumn("Date1", typeof(DateTime));
col.DateTimeMode = DataSetDateTime.Utc;
table.Columns.Add(col);

This shouldn't matter if you store dates in your dbase in UTC, like you should.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...