数据库中存储日期的字段类型到底应该用varchar还是datetime ?
背景: 前段时间在百度经验看到一篇文章《怎样在电脑右下角显示你(爱人)的名字》,之前也听过这个小技巧,但没真正动手设置过,所以出于好奇就实践了一下。 设置完毕后的效果如下,右下角的时间区域增加了我的名字 “Danny” : 以上为背景。 没想到这个小技
背景:
前段时间在百度经验看到一篇文章《怎样在电脑右下角显示你(爱人)的名字》,之前也听过这个小技巧,但没真正动手设置过,所以出于好奇就实践了一下。
设置完毕后的效果如下,右下角的时间区域增加了我的名字 “Danny” :
以上为背景。没想到这个小技巧给我带来了麻烦(当然也是一次学习和提高的机会)。
该字符串未被识别伪有效的DateTime
正在做的新闻发布系统,数据库中存储时间的字段类型为datetime类型,并且字段值都是在服务器端自动获取的。想在客户端以“yyyy-MM-dd HH:mm:ss”的格式显示时间时,出现了一个问题:“该字符串未被识别伪有效的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(),则不会产生此错误。于是可以知道,这里时间格式转化的过程是这样的:
在这个过程中,系统判断出从数据库中获取到的值为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类型。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. First open the mobile web browser, search for the Weibo web version, and click the avatar button in the upper left corner after entering. 2. Then click Settings in the upper right corner. 3. Click the version switching option in settings. 4. Then select the color version option in the version switch. 5. Click Search to enter the search page. 6. After entering the keywords, click Find People. 7. When the search completion interface appears, click Filter. 8. Finally, enter the specific date in the release time column and click Filter.

1. Let me first talk about the method I used at the beginning, maybe everyone is using it too. First, open [View]——]Remarks Template[. 2. A place where you can actually see the date after opening it. 3. Select it first and delete it. 4. After deleting, click [Close Master View]. 5. Open the print preview again and find that the date is still there. 6. In fact, this date was not deleted here. It should be in the [Handout Master]. Look at the picture below. 7. Delete the date after you find it. 8. Now when you open the preview and take a look, the date is no longer there. Note: In fact, this method is also very easy to remember, because the printed handouts are handouts, so you should look for the [Handout Master].

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Go functions can return multiple values of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.
