簡體   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