By using this site, you acknowledge that you have read and understand our Cookie policy, Privacy policy and Terms .

找了很久都没有找到合理的解释,幸好找到一篇文章,解答了这个问题,特收藏于此,以备参考。

http://www.xueit.com/html/2009-02/21_644_00.html

最近使用ASP.NET+SQLite数据库开发一个网站程序,结果在日期处理上出现了很头痛的问题,看下图

说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.FormatException: 该字符串未被识别为有效的 DateTime。

解决方案:

在日期保存到Sqlite数据库时转换一个类型,比如:string _now = System.DateTime.Now.ToString("s");

也就是说在.ToString()方法中加一个s,即可解决日期读取错误的问题。

简单代码示例:

string _indate = Request["indate"]; //输入的日期如:2009-2-21
DateTime _inTime = Convert.ToDateTime(_indate);

//如下是保存数据SQL语句

insert into 表(indate) values(‘“ + _inTime.ToString("s") + "');   //这里转换

之后日期保存在Sqlite数据库的内容为:

奇怪为什么日期成为:1899-12-30了,放心这是正常,看下面我读取日期出来的内容是什么?如下:

看,是正确的日期。

因为iso 8601的描述:(http://msdn.microsoft.com/zh-cn/library/ms187819.aspx)

给出了字符串示例:
* 2004-05-23T14:25:10
* 2004-05-23T14:25:10.487

所以Sqlite保存的日期要转为iso 8601标准字符串格式

使用 日期.ToString("s");这种方法转换成 iso 8601标准字符串格式了。



info Last modified by Raymond at 6 years ago * This page is subject to Site terms.

More from Kontext

visibility 13650
thumb_up 0
access_time 6 years ago

SQL Server Compact 4.0 (CE 4.0) is a free SQL Server embedded database ideal for building standalone and occasionally connected applications for mobile devices, desktops, Web clients and others. In one of my projects, I used it as the database for logging errors, which assumes the errors will onl...

open_in_new View open_in_new SQL Server

visibility 684
thumb_up 0
access_time 6 years ago

SQL Server provides a batch of great features to build robust, high-performance and scalable data solutions. ...

open_in_new View open_in_new SQL Server

visibility 1143
thumb_up 0
access_time 6 years ago

Serial: An Introduction to SQL Server Features Case Scenario In the previous articles of this serial, I’ve introduced how to use SQL Server as database for online transaction proces...

open_in_new View open_in_new SQL Server

visibility 4114
thumb_up 0
access_time 6 years ago

Serial: An Introduction to SQL Server Features Case Scenario For this ETL project, the requirements are listed below: Sales data will be pushed to specified shared fold...

open_in_new View open_in_new SQL Server

info About author

Kontext dark theme mode

Dark theme mode

Dark theme mode is available on Kontext.

Learn more arrow_forward
Kontext Column

Kontext Column

Created for everyone to publish data, programming and cloud related articles. Follow three steps to create your columns.

Learn more arrow_forward
info Follow us on Twitter to get the latest article updates. Follow us