1

我有一个这样的字符串:12/16/2011 12:00:00 AM
现在我只想显示日期部分,即12/16/2011在 Textview 上
并删除另一部分。我需要为此做些什么??

任何帮助将不胜感激。

4

6 回答 6

6

使用 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);
于 2012-05-02T11:58:04.567 回答
5
String str = "11/12/2011 12:20:10 AM";

    int i = str.indexOf(" ");
    str = str.substring(0,i);
    Log.i("TAG", str);
于 2012-05-02T11:57:53.030 回答
3

只有两个简单的可能性:

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];
于 2012-05-02T11:59:06.813 回答
1

您可以使用下面的代码来获取子字符串

String thisString="Hello world";

String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
于 2018-05-31T11:03:30.250 回答
0

使用正则表达式(比其他表达式更健壮 - 即使没有找到空格也能工作)

str.replaceAll(" .*", "");
于 2012-05-02T11:59:33.983 回答
0
myString = myString.substring(0, str.indexOf(" "));

或者

myString = myString.split(" ", 1)[0];
于 2012-05-02T12:14:46.047 回答