我有一个字符串,其中包含一个日期,例如 "01-01-2012",然后是一个空格和时间 "01:01:01"。完整的字符串为:"01-01-2012 01:01:01"。
我想从这个字符串中仅提取日期,最终可以得到 "01-01-2012",但不知道如何做。
以下是四种选项(后两个选项添加是为了让此答案包含其他回答中提供的选项):
SimpleDateFormat
)使用indexOf
查找第一个空格,并使用substring
获取前导子字符串:
int spaceIndex = text.indexOf(" ");
if (spaceIndex != -1)
{
text = text.substring(0, spaceIndex);
}
相信它以指定的格式是有效的,并且第一个空格始终在索引10处:
text = text.substring(0, 10);
将字符串按空格分割,然后取第一个结果(看起来对我来说效率有些低,但这会起作用...)
text = text.split(" ")[0];
你还需要考虑如果没有空格会发生什么。这是否意味着数据一开始就无效?你应该继续整个字符串吗?这将取决于您的情况。String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];
试试这个:
String date = s.substring(0, s.indexOf(" "));
String date = s.substring(0, 10);
或者使用StringUtils.substringBefore()
:
String date = StringUtils.substringBefore(s, " ");
+1
)是正确的,我想我们不需要日期后面的空格。 - Tomasz Nurkiewicz有很多方法可以做到这一点,一个非常简单的方法是在空格处拆分字符串并使用第一部分(即日期):
String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];
您可以使用substring仅提取日期:
String thedatetime = "01-01-2012 01:01:01";
String thedateonly = thedate.substring(0, 10);
public String getDateOnly(String fullDate){
String[] spl = fullDate.split(" ");
return spl[0];
}
你可以使用字符串操作 API 完成它:
String datetime = "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
String date = datetime.substring(0, spacePos - 1);
}
或者使用正则表达式:
Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime = "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
String date = m.group(1);
}
或者使用SimpleDateFormat
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();
/**
* @param dateTime format string
* @param type type of return value : "date" or "time"
* @return String value
*/
private String getFullDate(String dateTime, String type) {
String[] array = dateTime.split(" ");
if (type == "time") {
System.out.println("getDate: TIME: " + array[1]);
return array[1];
} else if (type == "date") {
System.out.println("getDate: DATE: " + array[0]);
return array[0];
} else {
System.out.println("NULL.");
return null;
}
}
/**
* @param datetime format string
* @return
*/
private String getOnlyDate(String datetime) {
String array[] = datetime.split("-");
System.out.println("getDate: DATE: " + array[0]);
return array[0];
}
希望我的回答能够对您有所帮助。