| | |
| | | import java.io.UnsupportedEncodingException; |
| | | import java.net.URLEncoder; |
| | | import java.sql.Timestamp; |
| | | import java.text.ParseException; |
| | | import java.text.SimpleDateFormat; |
| | | import java.time.Instant; |
| | | import java.util.Calendar; |
| | | import java.util.Date; |
| | | |
| | |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 计算 Date 到今天的天数(不足一天按一天算) |
| | | * @param date 要比较的日期(可为 null) |
| | | * @return 天数(至少为 1 天) |
| | | */ |
| | | public static long getDaysRoundedUp(Date date) { |
| | | if (date == null) { |
| | | return 0; // 处理 null,返回 -1 或根据业务调整 |
| | | } |
| | | // 获取当前时间(含时分秒) |
| | | Instant now = Instant.now(); |
| | | Instant dateInstant = date.toInstant(); |
| | | |
| | | // 计算毫秒差 |
| | | long millisDiff = now.toEpochMilli() - dateInstant.toEpochMilli(); |
| | | // 如果日期在未来,直接返回 1 天 |
| | | if (millisDiff <= 0) { |
| | | millisDiff = Math.abs(millisDiff); |
| | | //return 1; |
| | | } |
| | | |
| | | // 一天的毫秒数 |
| | | long millisPerDay = 24 * 60 * 60 * 1000; |
| | | |
| | | // 向上取整:不足一天按一天算 |
| | | return (long) Math.ceil((double) millisDiff / millisPerDay); |
| | | } |
| | | |
| | | |
| | | public static void main(String[] args) { |
| | | |
| | | System.out.println(dateToStr1(new Date())); |
| | | public static void main(String[] args) throws ParseException { |
| | | |
| | | |
| | | /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 指定格式 |
| | | |
| | | // 测试:今天(不足一天按一天算) |
| | | Date today = new Date(); |
| | | System.out.println("今天:" + getDaysRoundedUp(today)); // 输出:1 |
| | | |
| | | // 测试:昨天(23小时前) |
| | | String str = "2025-07-15 14:10:45"; |
| | | Date date = sdf.parse(str); |
| | | System.out.println("昨天(23小时前):" + getDaysRoundedUp(date)); // 输出:1 |
| | | |
| | | // 测试:3天前(72小时) |
| | | String str2 = "2025-07-18 16:10:45"; |
| | | Date date2 = sdf.parse(str2); |
| | | System.out.println("3天前:" + getDaysRoundedUp(date2)); // 输出:3 |
| | | |
| | | String str3 = "2025-07-19 16:10:45"; |
| | | Date date3 = sdf.parse(str3); |
| | | System.out.println("未来(1天后):" + getDaysRoundedUp(date3)); // 输出:1*/ |
| | | } |
| | | } |