search
HomeDatabaseMysql Tutorial数据库中存储日期的字段类型到底应该用varchar还是datetime ?

背景: 前段时间在百度经验看到一篇文章《怎样在电脑右下角显示你(爱人)的名字》,之前也听过这个小技巧,但没真正动手设置过,所以出于好奇就实践了一下。 设置完毕后的效果如下,右下角的时间区域增加了我的名字 “Danny” : 以上为背景。 没想到这个小技


       背景:

       前段时间在百度经验看到一篇文章《怎样在电脑右下角显示你(爱人)的名字》,之前也听过这个小技巧,但没真正动手设置过,所以出于好奇就实践了一下。

      设置完毕后的效果如下,右下角的时间区域增加了我的名字 “Danny” :

      数据库中存储日期的字段类型到底应该用varchar还是datetime ?


      以上为背景。没想到这个小技巧给我带来了麻烦(当然也是一次学习和提高的机会)。


      该字符串未被识别伪有效的DateTime

       正在做的新闻发布系统,数据库中存储时间的字段类型为datetime类型,并且字段值都是在服务器端自动获取的。想在客户端以“yyyy-MM-dd HH:mm:ss”的格式显示时间时,出现了一个问题:“该字符串未被识别伪有效的DateTime”:

         错误页面如下图:

         数据库中存储日期的字段类型到底应该用varchar还是datetime ?

        获取异常,异常提示为:

         数据库中存储日期的字段类型到底应该用varchar还是datetime ?

        出错关键代码为:    

lblCreateTime.Text = Convert.ToDateTime(news.CreateTime).ToString();  //【注】:lblCreate为前端显示页面一个Lable;news为查询后得到的“新闻”实体类,CreateTime为它的一个字段


        猜测是我本机电脑时间格式的问题,在客户端获取了一下时间news.CreateTime的值,格式为:“2014/8/23 星期六 Danny 13:10:14”,而该条记录的时间在数据库中存储的值为 “2014-08-2313:10:14”。经过测试,如果news.CreateTime在数据库中存储的类型为varchar(),则不会产生此错误。于是可以知道,这里时间格式转化的过程是这样的:

         数据库中存储日期的字段类型到底应该用varchar还是datetime ?

        在这个过程中,系统判断出从数据库中获取到的值为datetime类型,所以要将获取到的值(比如这里从数据库中获取的时间值为“2014-08-2313:10:14”)转化为本机的时间格式(比如我电脑的时间格式“2014/8/23 星期六 Danny13:10:14),在进行最后一步格式转化时,系统则无法识别用户自定义的时间格式(比如这里的“2014/8/23 星期六 Danny13:10:14),从而报错。


        在网上找了两篇总结Asp.net中时间格式转化的文章:asp.net 格式化时间日期Asp.net中时间格式化的几种方法。这么多种方法,大体上我把它分为两个方式:在界面代码(*.aspx)上转换 & 在后台代码(*.aspx.cs)上转换。


         解决方法

         解决这个问题用了两个办法:

        1、如果数据库中存储时间的数据类型为datetime,那就避免在后台代码(*.aspx.cs)中转化时间格式,将格式转化的任务放到界面代码(*.aspx)上

        比如上面的例子中,无论获取的时间是什么格式的,在后台不要对这个时间的值进行任何操作(比如赋值等,否则系统会将时间隐式转换),而是直接在界面代码(*.aspx)用DataBinder、Eval等方法来直接进行格式化

        后台关键代码:    

    <span style="white-space:pre">	</span>DataTable dt = new NewsManager().SelectById(newsid);     //这里得到的dt为从直接数据库中查询到的数据
    <span style="white-space:pre">	</span>    repNews.DataSource =dt;
            repNews.DataBind();

        前台关键代码:

<span style="white-space:pre">	</span><repeater id="repNews" runat="server">
            <itemtemplate>
                <p class="con_time">
                    发布时间: 
                           
                </p>
            </itemtemplate>
        </repeater>


        其实,大部分系统中的时间格式,那些格式转化函数还是“认识”的,但假如有的将自己的系统时间格式设置为“2014/8/23 星期六Danny 13:10:14”,有的设置为“2014/8/23 星期六胡玉洋 13:10:14”……,这些函数肯定猜不到那么多中自定义的情况。


        所以,在设计软件的过程中,最好把客户端这个因素刨除在外,保证各种使用环境的兼容性,时间在数据库中产生,同样显示时也只显示数据库中的时间(避免客户端的过滤)。

        2、将数据库中存储时间的数据类型改为varchar(),不过这时最好让这些时间是数据库中自动生成的(一个没有格式的输入也可能会导致输出错误),因为存储类型为varchar(),所以获取到的值也就被认为是一个字符串,这时在转换时间格式时就少了上图中【将获取的时间转化为客户端时间格式下的值】的步骤,直接将数据库中的时间字符串进行转化(这时那些转化函数是能识别数据库中的时间函数的),客户端的时间格式不再影响转换过程。


        不过数据库中存储时间的类型如果为字符型也会带来一些麻烦:

        数据库中的时间仅仅是用来显示、查找的,那么影响还不算大,但如果对时间字段进行一些算法如计算星期、DateDiff、DateAdd等,那就麻烦了,尤其实在大型数据查询中转换类型是会影响效率的


        总结

        数据库中存储日期的字段类型到底应该用varchar还是datetime ?这两种方法各有优势,datetime可以借用sql函数库中运算函数,增加了时间在各种运算上的效率;而varchar类型则可以在字符编码上显出优势。在 存储的时间将来不需要进行大量计算 的前提下,可以考虑选择varchar类型,反之,选择datetime类型。

        

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL String Types: Storage, Performance, and Best PracticesMySQL String Types: Storage, Performance, and Best PracticesMay 10, 2025 am 12:02 AM

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

Understanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreUnderstanding MySQL String Types: VARCHAR, TEXT, CHAR, and MoreMay 10, 2025 am 12:02 AM

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

What are the String Data Types in MySQL?What are the String Data Types in MySQL?May 10, 2025 am 12:01 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function