Here you can find the source of formatDateFromTo(LocalDateTime dateFrom, LocalDateTime dateTo)
Parameter | Description |
---|---|
dateFrom | LocalDateTime from. |
dateTo | LocalDateTime to. |
public static String formatDateFromTo(LocalDateTime dateFrom, LocalDateTime dateTo)
//package com.java2s; //License from project: Open Source License import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Main { private static final String DAYS = "days"; /**//from w w w .j a v a2s. c o m * @@author A0139812A * Formats a start date and end date to a date range, which will display only as much info as necessary. * @param dateFrom LocalDateTime from. * @param dateTo LocalDateTime to. * @return Formatted string. */ public static String formatDateFromTo(LocalDateTime dateFrom, LocalDateTime dateTo) { if (dateFrom == null && dateTo == null) { return ""; } else if (dateTo == null) { // No endDate return formatTime(dateFrom); } else if (dateFrom.isAfter(dateTo)) { // Unhandled error, just ignore endDate and assume it has no endDate return formatTime(dateFrom); } else if (dateFrom.toLocalDate().equals(dateTo.toLocalDate())) { return String.format("%s - %s", formatTime(dateFrom), formatTime(dateTo)); } else { return String.format("%s - %s", formatDateTime(dateFrom), formatDateTime(dateTo)); } } /** * @@author A0139812A * Formats a LocalDateTime to a 24-hour time. * * @param dateTime LocalDateTime to format. * @return 24-hour time formatted string. */ public static String formatTime(LocalDateTime dateTime) { if (dateTime == null) { return null; } return dateTime.toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm")); } /** * @@author A0139812A * Formats a LocalDateTime into short date + time format. * @param dateTime LocalDateTime to format. * @return Short date + time formatted string. */ public static String formatDateTime(LocalDateTime dateTime) { return String.format("%s %s", formatShortDate(dateTime), formatTime(dateTime)); } /** * @@author A0139812A * Formats a LocalDateTime to a short date. Excludes the day of week only if * the date is within 2-6 days from now. * * @param dateTime LocalDateTime to format. * @return Formatted shorten day. */ public static String formatShortDate(LocalDateTime dateTime) { if (dateTime == null) { return null; } LocalDate date = dateTime.toLocalDate(); long daysDifference = LocalDate.now().until(date, ChronoUnit.DAYS); String dateFormat; // Don't show dayOfWeek for days d, such that d = {n+2,...,n+6}, where n = date now if (daysDifference >= 2 && daysDifference <= 6) { dateFormat = "dd MMM"; } else { dateFormat = "E dd MMM"; } return date.format(DateTimeFormatter.ofPattern(dateFormat)); } }