{"id":22065554,"url":"https://github.com/karenpayneoregon/sql-server-datetime2","last_synced_at":"2026-02-03T04:32:43.698Z","repository":{"id":110840655,"uuid":"581814372","full_name":"karenpayneoregon/sql-server-datetime2","owner":"karenpayneoregon","description":"Learn about using datetime2 precision","archived":false,"fork":false,"pushed_at":"2024-11-08T13:55:34.000Z","size":320,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-23T10:52:58.482Z","etag":null,"topics":["csharp","datareader","datatable","datetime","datetime-format","datetime2","efcore7","precision","sqlserver"],"latest_commit_sha":null,"homepage":"https://dev.to/karenpayneoregon/sql-server-exploration-of-datetime27-precision-c-2l54","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/karenpayneoregon.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-12-24T12:43:14.000Z","updated_at":"2024-11-08T13:55:38.000Z","dependencies_parsed_at":null,"dependency_job_id":"43ab1e30-86d3-435d-af19-6815648d134b","html_url":"https://github.com/karenpayneoregon/sql-server-datetime2","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/karenpayneoregon/sql-server-datetime2","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-datetime2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-datetime2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-datetime2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-datetime2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/karenpayneoregon","download_url":"https://codeload.github.com/karenpayneoregon/sql-server-datetime2/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fsql-server-datetime2/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29032922,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-03T02:28:16.591Z","status":"ssl_error","status_checked_at":"2026-02-03T02:27:48.904Z","response_time":96,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","datareader","datatable","datetime","datetime-format","datetime2","efcore7","precision","sqlserver"],"created_at":"2024-11-30T19:19:29.425Z","updated_at":"2026-02-03T04:32:43.691Z","avatar_url":"https://github.com/karenpayneoregon.png","language":"C#","readme":"# SQL-Server: Exploration of datetime2(7) precision\n\n## Introduction\n\nIn this article with code samples, learn about using datetime2 precision.\n\n**What is datetime2?**\n\nDefines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.\n\n**Precision scale**\n\nWe tend to define a datetime2(**7**) where in this case **7** is the precision and can range from 0 to 7. This means in a table if the default 7 is not need, use the precision which works best for given business requirements or leave as 7.\n\nTypically developers don�t need to be concerned with milliseconds part of a date but when needed using datetime2 provides milliseconds. Write a query with a column of type datetime2 and milliseconds are display. Now write code using C# to return data from the same query to a DataTable, DataSet, DataReader or Entity Framework and note it appears milliseconds has been truncated. Below learn how to get full milliseconds in C# no matter how the data is retrieved and how to format milliseconds in a user interface.\n\n## Diving in working with datetime2 precision\n\nWhen working with [datetime2(7)](https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime2-transact-sql?view=sql-server-ver16) in a SQL-Server table we see time as hours, minutes, seconds and milliseconds.\n\n**Example table definition**\n\n\n![Figure2](assets/figure2.png)\n\nWrite a simple `SELECT` statement.\n\n```sql\nSELECT Id,\n       [User],\n       Created\nFROM dbo.AuditLog;\n```\n\nReturns\n\n![Figure3](assets/figure3.png)\n\nNow we know that milliseconds are properly stored, time to read the records into a C# application using either a DataReader, DataTable or Entity Framework Core and for the first record the expected value for Created column should be `2022-11-26 17:44:28.4006356` but what the DataReader, DataTable or Entity Framework Core returns is `2022-11-26 17:44:28.400`. This can be frustrating to a developer that does not understand what is happening.\n\n![Figure4](assets/figure4.png)\n\n\u003c/br\u003e\n\n![Figure5](assets/figure5.png)\n\n\nIf we look at `TimeOfDay.TotalSeconds` the `fraction` is out `milliseconds`. Knowing this let's create a languge extension to get milliseconds, the fraction part of TotalSeconds.\n\n\n```csharp\npublic static class Extensions\n{\n    public static decimal GetMilliseconds(this double sender) \n       =\u003e Convert.ToDecimal(sender) % 1.0m;\n}\n```\n\nWell that is partly there, let's get the method to return an `int` rather than  a `decimal`\n\n```csharp\npublic static class Extensions\n{\n    public static int GetMilliseconds(this double sender) \n        =\u003e Convert.ToInt32(Convert.ToString(Convert.ToDecimal(sender) % 1.0m, \n               CultureInfo.InvariantCulture).Replace(\"0.\", \"\"));\n}\n```\n\n**Usage**\n\n```csharp\nint milliseconds = created.TimeOfDay.TotalSeconds.GetMilliseconds();\n```\n\n:heavy_check_mark: Wait, we can do even better. Note .ToString is used as we do not want to add Milliseconds and Milliseconds, that is incorrect, instead perform string concatenation.\n\n```csharp\npublic static class Extensions\n{\n    public static int GetMilliseconds(this DateTime sender) \n        =\u003e Convert.ToInt32(sender.TimeOfDay.Milliseconds.ToString() + \n               sender.TimeOfDay.Milliseconds.ToString());\n}\n```\n\nPerhaps one more update, if the requirements is to get precision to 7 the last method does not but the following does.\n\n```csharp\npublic static class Extensions\n{\n    public static int GetMilliseconds7(this DateTime sender) \n        =\u003e Convert.ToInt32((sender.TimeOfDay.Milliseconds.ToString() + sender.TimeOfDay.Microseconds.ToString())\n            .PadRight(7, '0'));\n}\n```\n\nIn this case we use\n\n```csharp\ncreated.GetMilliseconds();\n```\n\nOr\n\n```csharp\ncreated.GetMilliseconds7();\n```\n\n\n## Formatting\n\nIf all that is needed is to format milliseconds and the precisions is unknown. First query the database using the following statement in SSMS.\n\n```sql\nSELECT \tTABLE_NAME,COLUMN_NAME,DATETIME_PRECISION FROM INFORMATION_SCHEMA.COLUMNS WHERE  DATA_TYPE = 'datetime2';\n```\n\nFor C# provided in the project `SqlServerLibrary` and used in the project `SqlServerDateTime2PrecisionApp` with a DataReader, DataTable and EF Core 7.\n\n```csharp\npublic static (List\u003cDateTimeInformation\u003e list, bool hasColumns) GetDateTimeInformation(string connectionString, string tableName)\n{\n    List\u003cDateTimeInformation\u003e dateTimeInfoList = new();\n    var sql =\n        \"SELECT TABLE_NAME,COLUMN_NAME,DATETIME_PRECISION \" + \n        \"FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE = 'datetime2' AND TABLE_NAME = @TableName;\";\n\n    using var cn = new SqlConnection(connectionString);\n    using var cmd = new SqlCommand(sql, cn);\n    cmd.Parameters.Add(\"@TableName\", SqlDbType.NChar).Value = tableName;\n\n    cn.Open();\n\n    var reader = cmd.ExecuteReader();\n    if (reader.HasRows)\n    {\n        while (reader.Read())\n        {\n            dateTimeInfoList.Add(new DateTimeInformation()\n            {\n                TableName = reader.GetString(0), \n                ColumnName = reader.GetString(1), \n                Precision = reader.GetInt16(2)\n            });\n        }\n\n        return (dateTimeInfoList, true);\n    }\n    else\n    {\n        return (null, false)!;\n    }\n}\n```\n\n\u003c/br\u003e\n\n\n![Figure1](assets/figure1.png)\n\n## Documentation\n\nMicrosoft docs for [datetime2](https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime2-transact-sql?view=sql-server-ver16)\n\n# You might also like\n- Working [with date time](https://github.com/karenpayneoregon/working-with-datetime)\n- Working with [DateOnly](https://github.com/karenpayneoregon/dateonly-primer) primer\n- EF Core: [Working with TimeOnly](https://github.com/karenpayneoregon/ef-core-dateonly-timeonly)\n- SQL-Server: [Computed columns](https://github.com/karenpayneoregon/sql-server-computed-columns) which includes working with dates.\n- [Writing SQL](https://github.com/karenpayneoregon/writing-sql-queries-csharp) for your application\n\n# Summary\n\nWith what has been presented code provided shows how to get milliseconds from a datetime(n) along with how to format datetime(n) where the n could be 7 or perhaps 4.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fsql-server-datetime2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkarenpayneoregon%2Fsql-server-datetime2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fsql-server-datetime2/lists"}