[英]How to limited String in Android
在我的應用程序中,我想向TextView
顯示一些文本(日期)。
我從服務器獲取了此文本,並且希望在TextView中顯示此文本。
我從服務器獲取此文本:
2017年12月16日
但我想顯示這樣的:
2017年
如何刪除16 Dec
?
嘗試這個
public static String getYyyy(String date) {
String time = date;
try {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
Date date1 = format.parse(date);
if (date1 != null) {
time = new SimpleDateFormat("yyyy").format(date1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
試試這個使用split()
java字符串中的split()方法有兩個簽名。
public String split(String regex)
和,
public String split(String regex, int limit)
在Java中,使用split字符串是使用
.split(" ")
,它根據提供的模式對string
進行拆分,並返回String數組。
樣例代碼
String date="16 Dec 2017";
String [] dateParts = date.split(" ");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
您可以使用“”即空格將字符串分開,嘗試用“”將字符串分開,如下所示:-
String date = "16 Dec 2017";
String[] date = date.split(" ");
//for only 2017 you can use date[2]
請注意,有幾種方法可以更優雅,更正確地執行此操作,通常使用Date對象並更改其外觀...
但是,如您所願,我的回答是:
我不會分裂,因為創建一個數組僅浪費一個元素是一種浪費...
您可以使用子字符串方法
String xdate = "16 Dec 2017";
System.out.println(xdate.substring(xdate.length() - 4, xdate.length()));
在Java 8中,您可以這樣做:
Date date = new Date(); //Create a Date object with date provided from TextBox
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
由於您只想要year int year = localDate.getYear();
會給你一年。
如果您想要日期的子字符串,其中只有Year即最后4個數字,請嘗試以下代碼
String date="16 Dec 2017";
int a = date.length();
String d = date.substring(a-4,a);
如果您有日期和時間或更多日期數據,也可以嘗試此操作,而不是拆分
String requested_date = "16 Dec 2017";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
Date dateObj = simpleDateFormat.parse(requested_date,new ParsePosition(0));
dateObj.getYear();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.