繁体   English   中英

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

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

实际上,我必须从联系人处查找今天的生日。 我有字符串变量,例如String value="2014-06-24".

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

使用SimpleDateFormate,如果没有得到,可以使用下面的给定方法

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

您可以使用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);

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

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))以此类推。

暂无
暂无

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

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