[英]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.