java对日期的处理

获取系统当前时间:

使用Date在java.uitl包下

//导入包
import java.util.Date;
public class Text {
    public static void main(String[] args) {
        //创建Date对象
        Date nowTime=new Date();
        //输出时间
        System.out.println(nowTime);//Sun Mar 20 13:51:48 CST 2022;
    }

}

这个输出的日期格式有点不符合我们的习惯:

使用SimpleDateFormat(在java.text包下)进行日期格式化:

yyyy 年 MM 月 dd 日

HH 时 mm 分 ss 秒 SSS 毫秒

例如:

//导入SimpleDateFormat包
import java.text.SimpleDateFormat;
//导入Date包
import java.util.Date;
public class Text {
    public static void main(String[] args) {
        //创建Date对象
        Date nowTime=new Date();
        //使用SimpleDateFormat方法进行日期格式化
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  SSS");
        //把时间转化为字符串格式
        String  time=s.format(nowTime);
        //输出
        System.out.println(time);//2022-03-20 14:03:23  471



    }

}

把日期字符串转换成Date型;

//导包
import java.text.ParseException;
//导入SimpleDateFormat包
import java.text.SimpleDateFormat;
//导入Date包
import java.util.Date;
public class Text {
    public static void main(String[] args) throws ParseException {
        String time="2020-8-8 12:08:08 666";
        //使用SimpleDateFormat方法进行日期格式化(字符串日期格式一定要与SimpleDateFormat格式的日期一致)
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date dateTime=s.parse(time);
        //输出
        System.out.println(dateTime);//Sat Aug 08 12:08:08 CST 2020
    }

}

获取从1970年1月1日 00:00:00: 000(北京时间从1970年1月1日08:00:00 000开始)到当前时间的毫秒总数

//导包
import java.text.ParseException;
public class Text {
    public static void main(String[] args) throws ParseException {
        //使用System.currentTimeMillis()统计时间
        long nowtime=System.currentTimeMillis();
        System.out.println(nowtime);//1647757065608

    }

}

使用例子:统计一个方法的运行时间:

//导包
import java.text.ParseException;
public class Text {
    public static void main(String[] args) throws ParseException {
        //使用System.currentTimeMillis()统计时间
        long begin=System.currentTimeMillis();//方法开始时间
        print();
        long end=System.currentTimeMillis();//方法结束时间
        System.out.println("耗费时长:"+(end-begin)+"毫秒");//耗费时长:36毫秒

    }
    public static void print(){
        for (int i = 0; i < 100; i++) {
            System.out.println("i="+i);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张同学%

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值