解析日期并将其存储在SQLite数据库中[英] Parsing Date and storing it in SQLite database

本文是小编为大家收集整理的关于解析日期并将其存储在SQLite数据库中的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在解析使用saxParser的XML文件,并在处理程序内部,我正在创建一个DatamEmbers的对象.

我的XML文件上的日期为此格式:2010-12-28.

我找不到如何将像这样的字符串转换为日期对象.而且我也不明白如何将其存储在SQLite数据库中,因为似乎有多种格式(带小时/分钟/etc.)

,我需要它存储在一个对象中,所以我可以计算时间表等.

有人可以帮助我吗?

推荐答案

您可以使用Java的简单日期格式将日期格式化为您可以用来进行计算的Date对象:

http://download.oracle.com/javase/1.4 .2/docs/api/java/text/simpledateformat.html

所需的解析字符串是"yyyy'-'MM'-'dd"

首先将其存储到SQLite数据库中,您有几个选项:

  • 将其存储为字符串并在出现时将其转换为日期对象
  • (首选)将其存储为UNIX时间戳(Date.getTime()自1970年以来为您提供毫秒的数量,您可以在DB中存储该值.)这种方式是首选,因为您不喜欢必须做这么多(相对昂贵的)转换.您可以在long时间戳值上简单执行基本操作.

使用SQLite的内置日期函数有几个其他选项(如在此处),但最终为您想要将其拉到Android/Java代码中,并将其操作为Date对象,您要将OT必须进行转换.

本文地址:https://www.itbaoku.cn/post/102416.html

问题描述

I'm parsing an xml file with SAXParser and inside the handler I'm creating objects with one of the datamembers being the date.

The date on my XML file is in this format: 2010-12-28.

I can't find how to turn a string like that into a Date object though. And I also don't understand how to store it in a SQLite database, because there seem to be many formats (ones with hour/minutes/etc.)

And I need it stored in an object so I can calculate timespans etc.

Can someone help me with this?

推荐答案

You can use Java's Simple Date Format to format your date into a Date object that you can use to do calculations and such:

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

The parse string you want is "yyyy'-'MM'-'dd"

As for storing it into the SQLite database, you have a couple of options:

  • Store it as a string and convert it back to a date object when it comes out
  • (Preferred) Store it as a unix timestamp (Date.getTime() gives you the number of milliseconds since 1970, and you can store that value in the DB.) This way is preferred because you don't have to do so many (relatively expensive) conversions. You can simple do basic operations on the long timestamp values.

There are a couple of other options using SQLite's built in date functions (as described here), but ultimately if you want to pull it into the Android/Java code and manipulate it as a Date object you're going ot have to do a conversion.