你还有几天过生日,Java常用类来告诉你!

任务描述
计算你的的生日还有多少天。

编程要求
键盘第一次输入的字符串为小明的生日日期;
键盘第二次输入的字符串为当前时间;
计算你的的生日还有多少天,如果天数为 0,输出:“小明今天生日”;如果不为 0 ,输出:“距离生日还有xx天”。

源程序:

package 包装类与常用类;
 /**
 * 使用 SimpleDateFormat 类格式化后输出 30 天后的时间信息。
 */
/**
 * 编写一个程序,计算小明的生日还有多少天
 *//**
 * 编写一个程序,计算小明的生日还有多少天
 */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class DistacnceOfBirthday {
    public static void main(String[] args) {
        // 请在下面的Begin-End之间编写正确的代码
        /********** Begin **********/
        Scanner scanner = new Scanner(System.in);
        String birth = scanner.next();
        String today = scanner.next();
        SimpleDateFormat sft = new SimpleDateFormat("yyyy年MM月dd日");
        Date birthDate = null;
        Date todayDate = null;
        try {
            birthDate = sft.parse(birth);
            todayDate = sft.parse(today);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cToday = Calendar.getInstance();
        Calendar cBirth = Calendar.getInstance();
        cBirth.setTime(birthDate); // 设置生日
        cToday.setTime(todayDate); // 设置当前日期
        cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年格式
        int days;
        if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
            // 生日已经过了,要算明年的了
            days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
            cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)+1); // 修改为明年的生日日期
            days += cBirth.get(Calendar.DAY_OF_YEAR);
        } else {
            // 生日还没过
            days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
        }
        // 输出结果
        if (days == 0) {
            System.out.print("小明今天生日");
        } else {
            System.out.print("距离生日还有" + days + "天");
        }
        /********** End **********/
    }
}

运行结果:
在这里插入图片描述

### Java 中的时间类概述 Java 提供了一系列用于处理日期和时间的类,这些类主要集中在 `java.time` 包中。自 Java 8 起引入的新 API 更加现代化、易用且功能强大。以下是几个常用的时间类及其使用方法: #### 1. **LocalDate** 表示不带时区的日期(年-月-日)。它主要用于记录生日、纪念日等仅需日期的信息。 ```java import java.time.LocalDate; public class LocalDateExample { public static void main(String[] args) { // 获取当前日期 LocalDate today = LocalDate.now(); System.out.println("今天的日期:" + today); // 创建特定日期 LocalDate specificDate = LocalDate.of(2023, 10, 5); System.out.println("指定的日期:" + specificDate); // 修改日期 LocalDate nextYear = today.plusYears(1); // 明年的今天 System.out.println("明年的今天:" + nextYear); } } ``` 上述代码展示了如何获取当前日期以及创建一个具体的日期对象[^3]。 --- #### 2. **LocalTime** 表示不带时区的时间(小时-分钟-秒),适用于只需要时间部分的应用场景。 ```java import java.time.LocalTime; public class LocalTimeExample { public static void main(String[] args) { // 获取当前时间 LocalTime now = LocalTime.now(); System.out.println("现在的时间:" + now); // 添加时间间隔 LocalTime later = now.plusHours(2).plusMinutes(30); System.out.println("两小时三十分钟后:" + later); } } ``` 通过此示例可以理解如何操作时间和增加时间间隔[^4]。 --- #### 3. ** LocalDateTime** 结合了 `LocalDate` 和 `LocalTime` 的特性,表示既包含日期又包含时间的对象。 ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeExample { public static void main(String[] args) { // 当前日期时间 LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("当前日期时间:" + currentDateTime); // 自定义格式化输出 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDate = currentDateTime.format(formatter); System.out.println("格式化的日期时间:" + formattedDate); } } ``` 这段代码演示了如何获取并格式化当前的日期时间[^5]。 --- #### 4. **Duration** 用于计算两个时间之间的差值,通常应用于时间段的操作。 ```java import java.time.Duration; import java.time.LocalTime; public class DurationExample { public static void main(String[] args) { LocalTime start = LocalTime.of(9, 0); LocalTime end = LocalTime.of(17, 0); Duration duration = Duration.between(start, end); long hoursBetween = duration.toHours(); // 计算相差多少小时 System.out.println("工作时间长度:" + hoursBetween + " 小时"); } } ``` 这里说明了如何利用 `Duration` 来测量两个时刻之间的时间跨度[^6]。 --- #### 5. **Period** 类似于 `Duration`,但它专注于日期而非时间,适合用来计算天数、月份或年份差异。 ```java import java.time.LocalDate; import java.time.Period; public class PeriodExample { public static void main(String[] args) { LocalDate startDate = LocalDate.of(2023, 1, 1); LocalDate endDate = LocalDate.of(2024, 1, 1); Period period = Period.between(startDate, endDate); int years = period.getYears(); int months = period.getMonths(); int days = period.getDays(); System.out.printf("起始日期到结束日期:%d 年 %d 个月 %d 天%n", years, months, days); } } ``` 以上例子解释了如何使用 `Period` 类来比较不同日期间的差距[^7]。 --- ### 总结 Java 的新时间 API (`java.time`) 是一套非常强大的工具集,能够满足大多数与时间相关的开发需求。无论是简单的日期显示还是复杂的时段运算,都可以借助这一系列类实现高效而精确的功能开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值