Date、SimpleDateFormat、Calendar的基本使用

本文介绍Java中日期时间的处理方式,包括使用Date类获取当前时间并转换为毫秒数,利用SimpleDateFormat类进行日期格式化及字符串解析,以及通过Calendar类获取和设置具体的日期时间信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Date类
1.Date date = new Date();
此时的date对象代表的是当前时间。
date.getTime();返回一个long型的数量代表 从1970年1月1日到当前时间所经历的毫秒数。

  public static void main(String[] args) {
    //日期类型:生产日期 下单时间 付款时间 预约时间
        //类Date表示特定的时间,精确到毫秒
        Date date1=new Date();//获取当前的时间
        System.out.println(date1);

        Date date2=new Date(1000);//
        System.out.println(date2);


    }

二、SimpleDateFormat类
1.SimpleDateFormat类是DateFormat类的子类,我们一般使用它。
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年MM月dd日 HH:mm:ss”);
我们一般使用这个构造方法来实例化SimpleDateFormat对象。
括号里面的yyyy年MM月dd日 HH:mm:ss;代表我们传入的Date对象转变为字符串时的格式。

DateFormate的format()方法来格式化时间,返回值类型为:String

2.使用parse()方法解析字符串并返回一个Date对象。

public static void main(String[] args) throws ParseException {
        Date date=new Date();
        //simpleDateFormat是DateFormat的子类,用来做日期和字符串之间的相互转换
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        //日期 格式化成 字符串
        String format=sdf.format(date);
        System.out.println(format);

        //字符串 解析成 日期
        String time="2022/10/15 08:10:20";
        Date date2=sdf.parse(time);
        System.out.println(date2);

    }

总结:
1.先使用Date date = new Date(); //创建一个现在的时间对象。
2.使用SimpleDateFormate sdf = new SimpleDateFormate(“你想要的需要的格式”);

三、Calendar类
1.Calendar是一个抽象类但是可以通过getInstance()方法来获得其实例化对象。
常用方法,get();

  public static void main(String[] args) {
        //Calendar的 getInstance 方法返回一个Calendar对象
        Calendar calendar=Calendar.getInstance();
        //获取当前时间
        Date time=calendar.getTime();
        System.out.println(time);
        //可以获取当前时间任何你想要获得的信息
        int year=calendar.get(Calendar.YEAR);
        System.out.println("年份"+year);
        int month=calendar.get(Calendar.MONTH);
        System.out.println("月份"+month);
        int dayOfYear=calendar.get(Calendar.DAY_OF_YEAR);
        System.out.println("本年第"+dayOfYear);
        // Calendar 可以通过get方法指定字段值来获取当前时间的一些信息
        //指定年月日 日分秒  月份0-11表示1-12
        calendar.set(2022,11,25,23,59,60);
        //获取指定的时间
        Date date1=calendar.getTime();
        System.out.println(date1);




    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值