简体   繁体   English

在SQL Server中将DateTime存储为字符串的最佳实践

[英]Best practice for storing DateTime as string in SQL Server

Let's say I MUST store a DateTime value as string in SQL Server in my web application. 假设我必须在Web应用程序中的SQL Server中将DateTime值存储为string This web app will be deployed to multiple servers behind a LB and share the same DB server. 该Web应用程序将部署到LB后的多台服务器,并共享同一台DB服务器。

This is a legacy project and apparently the guys developed it simply called ToString() on the DateTime instance, and this will format the datetime according to the culture setting of the machine; 这是一个遗留项目,很显然,人们在DateTime实例上开发了该项目,简称为ToString() ,它将根据计算机的区域性设置来格式化日期时间。 and when retrieving the datetime, a simple DateTime.Parse() would parse it correctly with the same culture setting implicitly. 当检索日期时间时,简单的DateTime.Parse()会隐式地使用相同的区域性设置正确地解析它。

However I do not believe this is a good approach, as this creates a dependency between the data and the culture setting of the machine, it means if multiple devs have different timezone settings they will be inserting the DateTime in different formats and this will error later when these values are parsed back to DateTime . 但是我不认为这是一个好方法,因为这会在数据和计算机的区域性设置之间建立依赖关系,这意味着,如果多个开发人员具有不同的时区设置,他们将以不同的格式插入DateTime ,稍后将出错将这些值解析回DateTime

I think a better approach would be to define a unified standard of the format of DateTime (eg dd/mm/yyyy), so that the data can work across different machines. 我认为更好的方法是定义DateTime格式的统一标准 (例如dd / mm / yyyy),以便数据可以在不同的机器上工作。 However I'd like to know if there is any downside or unexpected issues with this approach and would greatly appreciate your insight! 但是,我想知道这种方法是否存在任何缺点或意外问题,非常感谢您的见解!

The best format for storing a date/time as a string is an ISO 8601 standard format, either YYYY-MM-DD or YYYYMMDD (I prefer the version with the hyphens because I am a human being). 将日期/时间存储为字符串的最佳格式是ISO 8601标准格式,即YYYY-MM-DD或YYYYMMDD(我更喜欢带连字符的版本,因为我是人类)。

This format is standard, almost completely unambiguous (YYYYDDMM is almost unknown as a format). 此格式是标准格式,几乎是完全明确的(YYYYDDMM作为一种格式几乎是未知的)。 It also sorts correctly and can be used for between -type comparisons. 它还可以正确排序,并且可以用于类型between比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM