获取系统当前时间:
使用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);
}
}
}