转换Android的日期字符串到日期对象

转换Android的日期字符串到日期对象

本文介绍了转换Android的日期字符串到日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中,每一个事件的日期(如生日和纪念日)保存在字符串格式,例如: 2011-12-24。

这至少是我的电话的情况。其他一些手机也许存储这些日期等格式,如果他们有从阳历都不同的日历。

即使手机公历集,还有日期字符串以小时和分钟,没有。我得到这样的日期字符串,当我查询联系人表的事件:

<$p$p><$c$c>cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.ST‌​ART_DATE))

这将导致(例如):

2011-12-14或2011-12-24T00:00:00Z

您可以看到,有很多不同的可能形式。为了计算与日期,我需要将它们从字符串转换为Date对象,不用我?

我怎样才能做到这一点?

PS:我知道有一个解析功能的Java日期对象:

 日期格式myDateFormat =新的SimpleDateFormat(DD / MM / YY);
日期tempDate = myDateFormat.parse(24/12/2011);
 

但在Android的,我不知道哪种格式我会遇到,是吧?

解决方案

安卓适用于日期对象。任何时候你需要分析的日期从字符串是因为该日期已系列化,最有可能在一个文件中。在这种情况下,可以知道所使用的格式。 Date对象是用在preferences,日期对象用于几乎无处不在我能想到的,涉及到共享服务,运动,等等。这意味着,有几乎从来没有一个需要解析字符串的日期,除非,像我说你再有系列化源工作,从Web服务等看完如果你能告诉我们你的情况,你可能会得到更具体的答案。

您可以获取当前设置的日期格式是这样的:

 日期格式的日期格式= android.text.format.DateFormat.getDateFormat(getApplicationContext());
 

In Android, the date of every event (such as birthdays and anniversaries) is saved in String format, e.g. "2011-12-24".

This is at least the case for my phone. Some other phones may perhaps store these dates in other formats if they have a calendar different from the Gregorian one.

Even for phones with the Gregorian calendar set, there are date Strings with hours and minutes and without. I get such a date String when I query the contacts table for an event:

cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.ST‌​ART_DATE))

This results in (for example):

"2011-12-14" or "2011-12-24T00:00:00Z"

You can see that there are lots of different possible formats. In order to calculate with dates, I need to convert them from String to Date objects, needn't I?

How can I do this?

PS: I know there is a parse function for java date objects:

DateFormat myDateFormat = new SimpleDateFormat("dd/MM/yy");
Date tempDate = myDateFormat.parse("24/12/2011");

But in Android, I don't know which format I'll be confronted with, do I?

解决方案

Android works with date objects. Anytime you need to parse a date from string is because that date has been serialized, most likely in a file. In that case, you would know the format that was used. Date object is used in preferences, date object is used almost everywhere I can think of that relates to shared services, activites, etc. This means, there's almost never a need to parse string from date unless, like I said you're working with serialized source, reading it from a web service etc.If you can tell us your scenario, you might get more specific answer.

You can get the currently set date format like this:

DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());

这篇关于转换Android的日期字符串到日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:00