Reputation: 123
I am trying to output the time remaining to a certain date (15th of August in Madrid, Spain) and with my code I can get a TextView to display it correctly. However, it also displays milliseconds and seconds which I would like to remove, and also "months" that I would like to convert into days.
Could you give me a hand?
DateTimeZone timeZone = DateTimeZone.forID("Europe/Madrid");
DateTime target = new DateTime(2015, 8, 15, 0, 0, 0, timeZone);
DateTime now = new DateTime(timeZone);
Period period = new Period(now, target);
PeriodFormatter formatter = PeriodFormat.getDefault();
String output = formatter.print(period);
TextView tv = (TextView) v.findViewById(R.id.tv);
tv.setText(output);
Upvotes: 1
Views: 4579
Reputation: 44071
A pure Joda solution looks like:
DateTimeZone timeZone = DateTimeZone.forID("Europe/Madrid");
DateTime target = new DateTime(2015, 8, 15, 0, 0, 0, timeZone);
DateTime now = new DateTime(timeZone);
Period period = new Period(now, target);
PeriodFormatter formatter = PeriodFormat.getDefault();
String output = formatter.print(period);
System.out.println(output); // 4 weeks, 2 days, 17 hours, 2 minutes, 10 seconds and 817 milliseconds
period = new Period(
now,
target,
PeriodType.dayTime().withSecondsRemoved().withMillisRemoved());
output = formatter.print(period);
System.out.println(output); // 30 days and 17 hours
The decisive change is using a specialized variation of PeriodType.
As long as you only want full English words (using PeriodFormat.getDefault()
) Joda-Time is fine (there is built-in support for 9 languages only - other libs have better i18n-features). Otherwise, duration handling and formatting is not offered at all by standard Java as the other wrong answer of @VV pretends.
Upvotes: 1
Reputation: 1767
Try this
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String formattedDate = df.format(c.getTime());
try {
df.setTimeZone(TimeZone.getDefault());
long timeStamp = df.parse(formattedDate).getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 0