Home > OS >  Java Changing date format for a specific day
Java Changing date format for a specific day

Time:12-08

I want to write today's date in the following format using SimpleDateFormat:

Today, 13:14

On other days, I want to print it as date and time:

06.12.2021, 12:59

I can write in date and time format for previous days, but not in "Today [HOUR]" format during the day.

textViewDate.setText(new SimpleDateFormat("dd.MM.yyyy HH:mm")

Please guide. Thank you.

CodePudding user response:

I don't know a pre-existing date format that does what you want. So you have to do the conditional cases yourself.

If the date is in the "today" range (however you want to define that, regarding time zones etc.), generate the text using the "Today" format. If outside, use the generic format.

CodePudding user response:

if you are using java 8, you can use Date/Time API (LocalDate) to calculate the difference between two date and check if its the same date or not, based of the comparison choose your format Java Date Format

CodePudding user response:

java.time

This requires two formatters and an if statement.

Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first declare the two formatters.

private static final DateTimeFormatter TODAY_FORMATTER
        = DateTimeFormatter.ofPattern("'Today,' HH:mm", Locale.ENGLISH);
private static final DateTimeFormatter ANOTHER_DAY_FORMATTER
        = DateTimeFormatter.ofPattern("dd.MM.yyyy, HH:mm", Locale.ENGLISH);

To try them out with different dates and times:

    LocalDateTime[] dateTimes = {
            LocalDateTime.of(2021, Month.DECEMBER, 7, 23, 45),
            LocalDateTime.of(2021, Month.DECEMBER, 8, 12, 34),
            LocalDateTime.of(2021, Month.DECEMBER, 9, 04, 23)
    };

    LocalDate today = LocalDate.now(ZoneId.systemDefault());
    for (LocalDateTime ldt : dateTimes) {
        String formattedDateTime;
        if (ldt.toLocalDate().isEqual(today)) {
            formattedDateTime = ldt.format(TODAY_FORMATTER);
        }
        else {
            formattedDateTime = ldt.format(ANOTHER_DAY_FORMATTER);
        }
        System.out.println(formattedDateTime);
    }

When I ran today (December 8 in my time zone), I got:

07.12.2021, 23:45
Today, 12:34
09.12.2021, 04:23

If you insist on being old-fashioned, I am sure the same trick will work with SimpleDateFormat.

  • Related