在Android SQLite中处理日期的最佳方式 [英] Best way to work with dates in Android SQLite
问题描述
我在使用SQLite的Android应用程式中使用日期时遇到一些问题。
我有几个问题:
- 我应该使用什么类型来存储SQLite中的日期(text,integer,... )?
- 给定最好的方式来存储日期如何使用ContentValues正确地存储它?
- SQLite数据库?
- 如何在SQLite上进行SQL选择,按日期排序结果?
以UTC格式存储日期,如果您使用的是默认格式
从SQL Lite中检索日期作为字符串您可以通过日期列排序。然后可以使用Calendar或android.text.format.DateUtils.formatDateTime方法将其格式化/转换为本地区域化格式。
这里是一个区域化的格式化方法;
public static String formatDateTime(Context context,String timeToFormat){
String finalDateTime = ;
SimpleDateFormat iso8601Format = new SimpleDateFormat(
yyyy-MM-dd HH:mm:ss);
日期date = null;
if(timeToFormat!= null){
try {
date = iso8601Format.parse(timeToFormat);
} catch(ParseException e){
date = null;
}
if(date!= null){
long when = date.getTime();
int flags = 0;
flags | = android.text.format.DateUtils.FORMAT_SHOW_TIME;
flags | = android.text.format.DateUtils.FORMAT_SHOW_DATE;
flags | = android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
flags | = android.text.format.DateUtils.FORMAT_SHOW_YEAR;
finalDateTime = android.text.format.DateUtils.formatDateTime(context,
when + TimeZone.getDefault()。getOffset(when),flags);
}
}
return finalDateTime;
}
I'm having some trouble working with dates on my Android application that uses SQLite. I have a couple questions:
- What type should I use to store dates in SQLite (text, integer, ...)?
- Given the best way to store dates how do I store It properly using ContentValues?
- What's the best way to retrieve the date from the SQLite database?
- How to make a sql select on SQLite, ordering the results by date?
You can use a text field to store dates within SQLlite.
Storing dates in UTC format, the default if you use datetime('now') (yyyy-MM-dd HH:mm:ss) will then allow sorting by the date column.
Retrieving dates as strings from SQL Lite you can then format/convert them as required into local regionalised formats using the Calendar or the android.text.format.DateUtils.formatDateTime method.
Here's a regionalised formatter method I use;
public static String formatDateTime(Context context, String timeToFormat) {
String finalDateTime = "";
SimpleDateFormat iso8601Format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = null;
if (timeToFormat != null) {
try {
date = iso8601Format.parse(timeToFormat);
} catch (ParseException e) {
date = null;
}
if (date != null) {
long when = date.getTime();
int flags = 0;
flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;
finalDateTime = android.text.format.DateUtils.formatDateTime(context,
when + TimeZone.getDefault().getOffset(when), flags);
}
}
return finalDateTime;
}
这篇关于在Android SQLite中处理日期的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!