【问题标题】:How to force storage of datetime in milliseconds?如何以毫秒为单位强制存储日期时间?
【发布时间】:2021-05-25 19:38:41
【问题描述】:

任何人都可以就如何解决此问题提出建议吗?我需要将 DateTime 转换为自纪元以来的毫秒数,并将返回的值存储在数据库中。我遇到的问题是,无论我指定字段是什么数据类型,Azure 都会自动以实际日期格式存储返回的值 - 即,我正确地返回了 1613800800000,因为我已经对其进行了编码,但总是被存储无论如何在这种格式的数据库中,“Feb 20 2021 1”。

protected void testButton_Click(object sender, EventArgs e)
{
    TimeSpan reversion = new TimeSpan(0, 0, 0);
    DayOfWeek weekday = DateTime.Today.DayOfWeek;


    if(weekday == DayOfWeek.Tuesday)
    {

        DateTime utcTime = DateTime.UtcNow;
        TimeZoneInfo centralZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
        DateTime centralTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, centralZone).AddDays(-3);
        DateTime centralTimeConvert = TimeZoneInfo.ConvertTimeFromUtc(utcTime, centralZone).AddDays(-3);

        centralTime = centralTime.Date + reversion;
        centralTimeConvert = centralTimeConvert.Date + reversion;

        var centralTimeMilliseconds = centralTimeConvert.ToUniversalTime().Subtract(
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
        ).TotalMilliseconds;

        System.Data.SqlClient.SqlConnection connect = new System.Data.SqlClient.SqlConnection(masterConnectionString);
        System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();

        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = @"INSERT INTO StartEndTimes (StartTimeMilliseconds, StartTime) VALUES (@StartTimeMilliseconds, @StartTime)";

        command.Parameters.AddWithValue("@StartTime", centralTime);
        command.Parameters.AddWithValue("@StartTimeMilliseconds", centralTimeConvert);

        command.Connection = connect;
        connect.Open();
        command.ExecuteNonQuery();
        connect.Close();

        responseLabel.Text = centralTimeMilliseconds.ToString().Truncate(13);


    }

    else
    {
        

    }
}

我已经尝试将数据类型指定为 int、char 等以及所有其他选项,因此我希望有一种方法可以对存储格式进行硬编码,或者使用其他方法来停止自动日期格式化。

【问题讨论】:

  • 您能否发布表格 DDL 并在您的代码中包含该问题的完整重现?你所描述的听起来不太可能。
  • 一个滴答声是 100ns。所以要得到毫秒,你可以得到 Tick 然后除以 10,000。
  • 抛出了一个我不知道的异常,因为数据转换一直失败。通过这样做,我能够让它存储实际的毫秒值: string test = centralTimeMilliseconds.ToString().Truncate(13);

标签: c# sql azure azure-sql-database


【解决方案1】:

如果日期值存储为日期数据类型之一,则它没有“格式”,而是存储为一些二进制值。

格式仅在需要转换为文本时使用,例如向用户显示该值。或者当converting to JSON,这是一种文本格式。

【讨论】:

    猜你喜欢
    • 2022-11-27
    • 2018-08-05
    • 1970-01-01
    • 2016-09-05
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多