Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

How to format Simple Date Formatter in Java as dd-3 letter month-yyyy?

I have a simple date formatter with the following format:

private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(DATE_FORMAT);
//accessExpiryDate is a Date object
DATE_FORMATTER.format(accessExpiryDate);

And it is formatting the date as yyyy-MM-dd. But I want to format the date such as "1 Jun 2019". day + first 3 letter of the month + year.

How can i achieve that? Is there a simple way/method/class or should i write my custom date formatter method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

java.time

Don’t use Date and SimpleDateFormat. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. As Jon Skeet said, move to java.time, the modern Java date and time API, for a better experience.

    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("d MMM u", Locale.ENGLISH);
    LocalDate ld = LocalDate.of(2019, Month.JUNE, 1);
    System.out.println(ld.format(dateFormatter));

Output from this snippet is:

1 Jun 2019

A number of format pattern letters including M for month can yield either a number or a text depending on how many letters you put in the format pattern string (this is true for both DateTimeFormatter and the legacy SimpleDateFormat). So MM gives you two-digit month number, while MMM gives you a month abbreviation (often three letters, but could be longer or shorter in some languages).

If you are getting an old-fashioned Date object from a legacy API that you either cannot change or don’t want to upgrade just now, you may convert it like this:

    Date accessExpiryDate = getFromLegacyApi();
    LocalDate ld = accessExpiryDate.toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalDate();

The rest is as before. And now you’ve embarked on using the modern API and can migrate your code base in this direction at your own pace.

Link: Oracle tutorial: Date Time explaining how to use java.time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...