How do you format the day of the month to say 11th, 21st or 23rd (ordinal indicator)?
// https://github.com/google/guava
import static com.google.common.base.Preconditions.*;
String getDayOfMonthSuffix(final int n) {
checkArgument(n >= 1 && n <= 31, "illegal day of month: " + n);
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
The table from @kaliatech is nice, but since the same information is repeated, it opens the chance for a bug. Such a bug actually exists in the table for 7tn
, 17tn
, and 27tn
(this bug might get fixed as time goes on because of the fluid nature of StackOverflow, so check the version history on the answer to see the error).
How do you format the day of the month to say “11th”, “21st” or “23rd” in Dart?
Try out this package, Jiffy, inspired by momentjs.
Just simply add the do
date pattern. See below
Jiffy([2014, 4, 23]).format("EEEE MMMM do, yyyy"); // Wednesday April 23rd, 2014
You can also add your DateTime object
Jiffy(DateTime(2014, 4, 23)).format("EEEE MMMM do, yyyy"); // Wednesday April 23rd, 2014
Parsing a date’s ordinal indicator ( st, nd, rd, th ) in a date-time string
Java's SimpleDateFormat doesn't support an ordinal suffix, but the ordinal suffix is just eye candy - it is redundant and can easily be removed to allow a straightforward parse:
Date date = new SimpleDateFormat("MMM dd yyyy hh:mma")
.parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)", ""));
The replace regex is so simple because those sequences won't appear anywhere else in a valid date.
To handle any language that appends any length of ordinal indicator characters from any language as a suffix:
Date date = new SimpleDateFormat("MMM dd yyyy hh:mma")
.parse(str.replaceAll("(?<=\\d)(?=\\D* \\d+ )\\p{L}+", ""));
Some languages, eg Mandarin, prepend their ordinal indicator, but that could be handled too using an alternation - left as an exercise for the reader :)
define the date format java 'rd' 'st' 'th' 'nd'
SimpleDateFormat
doesn't seem to easily handle day numbers followed by "st" "th" etc. A simple solution would be remove that part of the original string. E.g.
int comma = original.lastIndexOf(',');
String stringDate =
original.substring(0, comma - 2) +
original.substring(comma + 1);
After that just use this format on stringDate
:
SimpleDateFormat("EE, MM, dd, hh:mm")
Formatting string to date in java
You can use a DateTimeFormatterBuilder
to create a DateTimeFormatter
that can parse days-of-month that have the "st", "nd", "rd" and "th" suffixes, and also lowercase AMPM.
// first create a map containing mapping the days of month to the suffixes
HashMap<Long, String> map = new HashMap<>();
for (long i = 1 ; i <= 31 ; i++) {
if (i == 1 || i == 21 || i == 31) {
map.put(i, i + "st");
} else if (i == 2 || i == 22){
map.put(i, i + "nd");
} else if (i == 3 || i == 23) {
map.put(i, i + "rd");
} else {
map.put(i, i + "th");
}
}
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendPattern("MMMM ")
.appendText(ChronoField.DAY_OF_MONTH, map) // here we use the map
.appendPattern(" yyyy HH:mm")
.appendText(ChronoField.AMPM_OF_DAY, Map.of(0L, "am", 1L, "pm")) // here we handle the lowercase AM PM
.toFormatter(Locale.US);
Usage:
LocalDateTime datetime = LocalDateTime.parse("April 5th 2021 12:30pm", dateFormatter);
How to get the ordinal indicator using time.Format()?
The support for the ordinal indicator is not there in the standard library. You can either implement the same yourself by taking help from this answer or use a third-party package.
There is a third-party package available for Go to convert the input integer to a string with the correct ordinal indicator; take a look at go-humanize.
Also, if you look under the hood at the implementation of go-humanize's support for the ordinal indicator; you'd notice that is very simple so I'd prefer maybe just implement it yourself by referring to both implementations I have linked. Refer: https://github.com/dustin/go-humanize/blob/v1.0.0/ordinals.go#L8
Or, go use go-humanize.
How to get day of month in 20th format in java?
check this first where you are using.
if(value <=30){
getOrdinalFor(value)
}else{
return "st";
}
here is your core logic
public static String getOrdinalFor(int value) {
int tenRemainder = value % 20;
switch (tenRemainder) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
Related Topics
How to Put a Control in the Jtableheader of a Jtable
Get a List of All Threads Currently Running in Java
Regexp Java For Password Validation
MySQL Jdbc Driver 5.1.33 - Time Zone Issue
How to Extract Numbers from a String and Get an Array of Ints
How to Read a File from Jar in Java
How to Enter Quotes in a Java String
Difference Between Fetchtype Lazy and Eager in Java Persistence API
Java.Util.Date VS Java.Sql.Date
How to Convert Epoch to MySQL Timestamp in Java