我有一个这样的字符串:12/16/2011 12:00:00 AM
现在我只想显示日期部分,即12/16/2011
在 Textview 上
并删除另一部分。我需要为此做些什么??
任何帮助将不胜感激。
使用 java.text.DateFormat 将 String 解析为 Date,然后重新格式化以使用另一个 DateFormat 显示它:
DateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
inputFormat.setLenient(false);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy");
outputFormat.setLenient(false);
Date d = inputFormat.parse("12/16/2011 12:00:00 AM");
String s = outputFormat.format(d);
String str = "11/12/2011 12:20:10 AM";
int i = str.indexOf(" ");
str = str.substring(0,i);
Log.i("TAG", str);
只有两个简单的可能性:
String str = "12/16/2011 12:00:00 AM";
// method 1: String.substring with String.indexOf
str.substring(0, str.indexOf(' '));
// method 2: String.split, with limit 1 to ignore everything else
str.split(" ", 1)[0];
您可以使用下面的代码来获取子字符串
String thisString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
使用正则表达式(比其他表达式更健壮 - 即使没有找到空格也能工作)
str.replaceAll(" .*", "");
myString = myString.substring(0, str.indexOf(" "));
或者
myString = myString.split(" ", 1)[0];