I am using the SimpleDateFormatter
public static final DateFormat DATE_FORMAT_FULL_FULL_SPACES =
new SimpleDateFormat(\"dd MMMM yyyy\", Local
The superscript part isn't the first tricky part here - although it's not clear how you'd want that to be represented anyway (HTML with <sup>
tags? something else?)
The first tricky part is knowing how to get the ordinal (st
, nd
, rd
, th
) and doing that appropriately for different cultures (which can have very different rules). This isn't something that SimpleDateFormat
supports, as far as I'm aware. You should also be aware that different cultures might not use dd MMMM yyyy
as their normal full date format - it could look very odd to some people.
I would think very carefully about:
If you only need to handle English, then the ordinal part isn't too hard (you can probably find examples of a String getOrdinal(int value)
method online, or write your own in 5 minutes). If you're also happy to always use a "day first" format, then you'd probably only need to format the month and year in SimpleDateFormat
, e.g.
public String formatWithOrdinal(Calendar calendar) {
DateFormat formatter = new SimpleDateFormat(" MMMM yyyy", Locale.getDefault());
formatter.setTimeZone(calendar.getTimeZone());
int day = calendar.get(Calendar.DATE);
return day + toSuperscript(getOrdinal(day)) + formatter.format(calendar.getTime());
}
Where toSuperscript
would use HTML or whatever you need to superscript the value.
In short, you have a lot of separable concerns here - I strongly suggest you separate them, work out your exact requirements, and then implement them as simply as you can.
Create these methods
private String getFormatedDate(){
String dayNumberSuffix = getDayNumberSuffix(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
SimpleDateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
return dateFormat.format(Calendar.getInstance().getTime());
}
private String getDayNumberSuffix(int day) {
if (day >= 11 && day <= 13) {
return "<sup>th</sup>";
}
switch (day % 10) {
case 1:
return "<sup>st</sup>";
case 2:
return "<sup>nd</sup>";
case 3:
return "<sup>rd</sup>";
default:
return "<sup>th</sup>";
}
}
How to call?
String str = getFormatedDate();
txtDate.setText(Html.fromHtml(str));
OutPut :