Java时间和日期的处理

1.Date类

构造方法

  • 第一个构造函数使用当前日期和时间来初始化对象。
    Date( )
  • 第二个构造函数接收一个参数,该参数是从1970年1月1日起的毫秒数。
    Date(long millisec)

常用方法

  • long getTime( )
    返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
  • String toString( )
    把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中:dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat)。
public class Test {
    public static void main(String[] args) {
        Date now = new Date();  //获取当前时间
        System.out.println(now.getTime());
        System.out.println(now);    //CST表示China Standard Time 即中国标准时间
    }
}

执行结果为:
1631023915763
Tue Sep 07 22:11:55 CST 2021

2.SimpleDateFormat 格式化日期

Date类的toString方法输出的结果通常不符合中国人的阅读习惯,因此常常需要对其进行格式化输出。

public class Test {
    public static void main(String[] args) {
        Date now = new Date();  //获取当前时间
        SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
        System.out.println("当前时间为 " + sd.format(now));
    }
}

yyyy和MM为日期和时间的格式化编码;使用时记住常见的几个即可。
SimpleDateFormat类的parse()方法用来解析字符串为时间,对字符串表示时间的处理中也较为常用

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入时间yyyy-MM-dd");
        String str = sc.nextLine();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }finally {
            System.out.println(date);
        }
    }
}

3.Calendar类

  • 创建一个代表系统当前日期的Calendar对象
    Calendar c = Calendar.getInstance();//默认是当前日期
public class Test {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);
        System.out.println(calendar.get(Calendar.YEAR));    //获取年份
        System.out.println(calendar.get(Calendar.MONTH)+1); //获取月份
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));    //获取几号
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK)-1);   //获取星期几
    }
}

此处有两个小坑需要注意
Calendar类获取月份时要加1
Calendar类获取星期几要减1

	/**
     * Field number for <code>get</code> and <code>set</code> indicating the
     * month. This is a calendar-specific value. The first month of
     * the year in the Gregorian and Julian calendars is
     * <code>JANUARY</code> which is 0; the last depends on the number
     * of months in a year.
     * /

Calendar类中一月的值为0,为符合日常习惯需要加1
Java中Calendar.DAY_OF_WEEK其实表示:一周中的第几天,所以他会受到 第一天是星期几 的影响。该类默认星期天为第一天,故需要减1。

4. LocalDate/LocalTime/LocalDateTime类

  • java.time.LocalDate ->只对年月日做出处理
  • java.time.LocalTime ->只对时分秒纳秒做出处理
  • java.time.LocalDateTime ->同时可以处理年月日和时分秒
    相比Date类,线程安全;相比Calendar类,获取月份和星期更加符合日常习惯,所以JDK1.8后建议使用LocalDate/LocalTime类对事件和日期进行处理。
public class Test {
    public static void main(String[] args) {
    	//三种创建LocalDate实例的方法
        LocalDate now = LocalDate.now(); //获取当前日期
        LocalDate date = LocalDate.of(2018, 7, 1);
        LocalDate date1 = LocalDate.parse("1996-09-19");
        System.out.println(date1);
        //三种创建LocalTime实例的方法
        LocalTime time = LocalTime.now();//当前时间
        LocalTime ofTime = LocalTime.of(16,30,25);
        LocalTime parseTime = LocalTime.parse("12:00:01");

        int year = now.getYear(); //获取年
        int month = now.getMonthValue();    //获取月份
        int day = now.getDayOfMonth();  //获取天
        System.out.println(year + " " + month + " " + day);

        int hour = time.getHour();  //获取时
        int minute = time.getMinute();  //获取分
        int second = time.getSecond();  //获取秒
        System.out.println(hour + " " + minute + " " + second);

    }
}

执行结果
1996-09-19
2021 9 8
9 20 58

此外还有获取当月第一天、当月最后一天等实用的小方法可以直接去使用。

public class Test {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        // 取本月第1天:
        LocalDate firstDayOfThisMonth = date.with(TemporalAdjusters.firstDayOfMonth()); 
        // 取本月第2天:
        LocalDate secondDayOfThisMonth = date.withDayOfMonth(2); // 
        // 取本月最后一天,再也不用计算是28,29,30还是31:
        LocalDate lastDayOfThisMonth = date.with(TemporalAdjusters.lastDayOfMonth()); 
        // 取下一天:
        LocalDate firstDayOfNextMonth = lastDayOfThisMonth.plusDays(1); 
        LocalDate firstMondayOf2017 = LocalDate.parse("2017-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); // 2017-01-02
        //输出
        System.out.println(firstDayOfThisMonth);
        System.out.println(secondDayOfThisMonth);
        System.out.println(lastDayOfThisMonth);
        System.out.println(firstDayOfNextMonth);
        System.out.println(firstMondayOf2017);
    }
}

执行结果
2021-09-01
2021-09-02
2021-09-30
2021-10-01
2017-01-02
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值