简体   繁体   English

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

[英]How to extract the substring from the string?

Actually i have to find today's birthday from contacts. 实际上,我必须从联系人处查找今天的生日。 I have the string variable like String value="2014-06-24". 我有字符串变量,例如String value="2014-06-24".

I want to get the month and date of the of the string variable to compare with today date to find the birthday. 我想获取字符串变量的月份和日期,以与今天的日期进行比较以查找生日。 Or it has any other methods? 还是有其他方法?

Use SimpleDateFormate, if you don not get you can use bellow given method 使用SimpleDateFormate,如果没有得到,可以使用下面的给定方法

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

You can use SimpleDateFormat to parse dates like this: 您可以使用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();
}

When you have Date objects you can compare them with before() and after() like this: 当您拥有Date对象时,可以将它们与before()after()进行比较,如下所示:

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

You can use a Calendar object to get further information from the Date object. 您可以使用Calendar对象从Date对象获取更多信息。

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

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

You can use following way to find date and month from value string: 您可以使用以下方法从值字符串中查找日期和月份:

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);

then 然后

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

then you can use date comparison like : 那么您可以使用日期比较:

if(date.before(today) || date.after(today)) and so on for your next operation. if(date.before(today) || date.after(today))以此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM