问题描述
当我需要存储时间/日期信息时,如何存储在数据库中最好?
如果我将它们存储为 String
表示例如获取当前时间戳(例如使用 Date
)并将 String
表示存储在DB中是个好主意? br>
这是什么最好的做法?什么是缺点?
When I need to store time/date information, how is it best to be stored in a database?
If I store them as a String
representation e.g. get current timestamp (using Date
for example) and store the String
representation in the DB is it a good idea?
What is the best practice for this? What are any cons?
推荐答案
最佳做法是使用 TIMESTAMP
或 DATE
键入数据库。所有主要数据库供应商都支持这些SQL标准数据类型。
The best practice is to use a TIMESTAMP
or DATE
type in the database. All major database vendors support these SQL standard data types.
除了性能和存储优化,您将获得更多的表现力,您将能够使用大量的datetime操作函数和操作直接在数据库中,这取决于您使用的数据库。考虑比较日期,添加日期,向日期添加时间间隔(例如,明天是什么日期)等。
Apart from performance and storage optimisation, you'll gain expressiveness and you'll be able to use a lot of datetime manipulation functions and operations directly in the database, depending on the database you're using. Think about comparing dates, adding dates, adding intervals to dates (e.g. what day is tomorrow), etc...
请注意...
- 如果您使用Oracle,请注意
DATE
也包含时间信息 - 如果您使用SQLite,请注意datetime类型可能具有数字或文本相似性。也就是说
- 如果您使用的是SQL Server,Sybase(ASE和SQL Anywhere),SQLite,方言特定版本的
TIMESTAMP
数据类型调用DATETIME
(SQL Server的TIMESTAMP
实际上是VARBINARY(8)
) - 至少H2,HSQLDB,MySQL,Sybase SQL Anywhere支持
TIMESTAMP
和DATETIME
数据类型同义词。
- If you're using Oracle, beware that
DATE
also contains time information - If you're using SQLite, beware that datetime types may have numeric or text affinity. I.e. they're stored as numbers or text.
- If you're using SQL Server, Sybase (ASE and SQL Anywhere), SQLite, the dialect-specific version of the
TIMESTAMP
data type is calledDATETIME
(SQL Server'sTIMESTAMP
is actually aVARBINARY(8)
) - At least H2, HSQLDB, MySQL, Sybase SQL Anywhere support both
TIMESTAMP
andDATETIME
data type synonyms.
这篇关于如何在数据库中最好存储时间戳或日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!