[英]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.