如何从字符串中提取子字符串?

时间:2014-06-24 09:15:55

标签: android string contacts

实际上我必须从联系人那里找到今天的生日。我有字符串变量之类的     String value="2014-06-24".

我想获取字符串变量的月份和日期以与今天的日期进行比较以查找生日。或者它有其他方法吗?

3 个答案:

答案 0 :(得分:4)

使用SimpleDateFormat,如果没有,可以使用下面给出的方法

String[] arr = yourStringDate.split("-");
String year = arr[0];
String month = arr[1];
String day = arr[2];

答案 1 :(得分:1)

您可以使用SimpleDateFormat来解析这样的日期:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date date = dateFormat.parse("2014-06-24");
} catch (ParseException e) {
    // This exception occurs when the String could not be parsed!
    e.printStackTrace();
}

如果您有Date个对象,可以将它们与before()after()进行比较,如下所示:

if(dateA.after(dateB)) {
    // dateA is after dateB
} else {
    // dateA is before dateB
}

您可以使用Calendar对象从Date对象获取更多信息。

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);

答案 2 :(得分:0)

您可以使用以下方式从值字符串中查找日期和月份:

Date date = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
    date = formatter.parse(value);
} catch (ParseException e) {
    // This exception occurs when the String could not be parsed!
    e.printStackTrace();
}

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int birthDay = cal.get(Calendar.DATE);
int birthMonth = cal.get(Calendar.MONTH);

然后

Calendar currentCal = Calendar.getInstance();
Date today =  currentCal.getTime();

然后您可以使用日期比较,如:

if(date.before(today) || date.after(today))等等,以便进行下一次操作。

相关问题