How to format dates correctly when I use getAttributeValue?

92 views Asked by At

I have an xml file where there is a date attribute and use XmlPullParser to display data in a list that include dates "yyy/MM/dd HH:mm", but I want to condition to choose only the data from the last 30 days and for that I compare dates that are in the xml file. The problem is when I want to format the file date to "yyy/MM/dd". I do the next code but it's not works. what should I do to format the date correctly?

SimpleDateFormat sdfDateBefore = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
String date = xpp.getAttributeValue(null, "fecha");
String DateFile = sdfDateBefore.format(date);
1

There are 1 answers

0
Paul Proaño On

I could resolve as follows: first I had to convert the original string value in a Date object and then a String object.

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);