Java常用日期操作

1.Date:

  @Test
    public void testOne(){
        Date date=new Date(System.currentTimeMillis());
        //获得毫秒值
        System.out.println(date.getTime());
        //2021-9-3 11:07:32
        System.out.println(date.toLocaleString());
    }

2.sql包下的几个日期操作:

@Test
    public void testComparm(){
        //返回当前时间HH-mm-ss
        Time time=new Time(System.currentTimeMillis());
        System.out.println(time.getTime());

        //返回当前日期:yyyy-MM-dd
        java.sql.Date date=new java.sql.Date(System.currentTimeMillis());
        System.out.println(date);

        //返回当前:yyyy-MM-dd HH-mm-ss
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
        System.out.println(timestamp);

    }

3.对Date类进行操作和设置当前日期的年月日:

@Test
    //对当前日期进行加减运算
    public void testCalendar(){
        //标准日历测试
        Calendar calendar=new GregorianCalendar();
        //设置日历时间
        calendar.set(Calendar.YEAR,2021);
        calendar.set(Calendar.MONTH,9);
        calendar.set(Calendar.DATE,3);

        //对传过来的date日期进行加减运算
        calendar.setTime(new Date(System.currentTimeMillis()-60*1000*60*24*2L));
        calendar.add(Calendar.DATE,-2);
        System.out.println(calendar.getTime().toLocaleString());
    }

4.获得当前年月日,包括单独的年,月,日.

 @Test
    //获得当前年月日
    public void localDate(){
        LocalDate localDate=LocalDate.now();
        //2021-09-03
        System.out.println(localDate);
        System.out.println(localDate.getMonthValue());
        System.out.println(localDate.getDayOfYear());
        System.out.println(localDate.getYear());
    }

5.获得当前时分秒,包括单独的时,分,秒:

@Test
    //获取当前时分秒
    public void localTime(){
        LocalTime localTime=LocalTime.now();
        System.out.println(localTime);
        //HH:12 mm:2 ss:48
        System.out.println("HH:"+localTime.getHour()+" mm:"+localTime.getMinute()+" ss:"+localTime.getSecond());
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值