[英]Android : date format in a String
由於這些日期的格式,我在排序日期時遇到問題。
我獲得了日期:
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
我用這些值構建一個String。
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
問題是,如果月份是例如2月,則mMonth值為2.因此,在我的列表中,有十月(10)之類的月份。
我需要的是像月和日那樣形成像MM和dd。 但我不知道如何在我的情況下這樣做。
編輯 :
我通過使用如上所述的DateFormat解決了這個問題。
我替換了這個:
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
這樣 :
Date date = new Date(mYear - 1900, mMonth, mDay);
dateFacDB = DateFormat.format("yyyy.MM.dd", date).toString();
它有效。 感謝大家的幫助:)
這是將Date轉換為String的簡單方法:
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");
String strDt = simpleDate.format(dt);
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
String timestamp = simpleDateFormat.format(now);
這些可能會派上用場
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ");
此格式等於 - >“2016-01-01T09:30:00.000000 + 01:00”
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
此格式等於 - >“2016-06-01T09:30:00 + 01:00”
您需要對日期進行排序,而不是字符串。 另外,你聽說過DateFormat嗎? 它可以滿足您的所有需求。
這是日期格式的示例
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
如果我理解你的問題,你創建一個日期列表,因為它們是字符串,它們按字典順序排列,這意味着你將在2月之前(10之前的10)獲得。
如果我是你,我會將我的結果存儲在一個容器中,我控制插入點(如數組列表)或我可以控制排序算法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.