【问题标题】:How to format dates correctly when I use getAttributeValue?使用 getAttributeValue 时如何正确格式化日期?
【发布时间】:2014-11-23 22:30:10
【问题描述】:
我有一个 xml 文件,其中有一个日期属性,并使用 XmlPullParser 在包含日期“yyy/MM/dd HH:mm”的列表中显示数据,但我想条件是只选择最后一个数据30 天,为此我比较了 xml 文件中的日期。问题是当我想将文件日期格式化为“yyy/MM/dd”时。我做了下一个代码,但它不起作用。我应该怎么做才能正确格式化日期?
SimpleDateFormat sdfDateBefore = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
String date = xpp.getAttributeValue(null, "fecha");
String DateFile = sdfDateBefore.format(date);
【问题讨论】:
标签:
android
simpledateformat
xmlpullparser
【解决方案1】:
我可以解决如下:首先我必须将原始字符串值转换为 Date 对象,然后转换为 String 对象。
SimpleDateFormat sdfDateBefore = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);
sdfDateBefore.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateTodayFile = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
String fechaFile = xpp.getAttributeValue(null, "fecha");
Date date = null;
try {
date = sdfDateBefore.parse(fechaFile);
} catch (ParseException e) {
e.printStackTrace();
}
String DateFile = dateTodayFile.format(date);