目录
一:简单的测试
System.currentTimeMillis()返回当前时刻的毫秒数
package com.changYongLei;
public class TestDate {
public static void main(String[] args) {
//包装类转为基本类型
long a=Long.MAX_VALUE/(1000l*3600*24*365);//大约在2.9亿年后
long time=System.currentTimeMillis();//代表当前时刻的毫秒数
System.out.println(a);
System.out.println(time);
}
}
二:java.util.Date
三:DateFormat时间格式化类
格式化字符的含义(不需要记)
DateFormat是抽象类,不能够创建对象,所以我们用他的子类SimpleDateFormat来创建对象
parse和format函数
format: 按指定的目标格式把Date对象转换为String
parse: 按指定的源格式把String转换为Date对象
下面看代码
package com.changYongLei;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
/**
* 测试时间对象和字符串的相互转化
* 使用 DateFormat,SimpleDateFormat
*/
public class DateFormat {
public static void main(String[] args) throws ParseException {//将异常直接丢出去
SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//固定的格式
//字符串转为Date对象
//parse: 按指定的源格式把String转换为Date对象
Date ss= s.parse("2021-9-14 13:51:52");
System.out.println(ss.getTime());
//Date对象转为字符串
Date d=new Date(1000l*3600*24*365*52);
//format: 按指定的目标格式把Date对象转换为String
String dd=s.format(d);
System.out.println(dd);
}
}