-
计算机中时间原点
1970年1月1日 00:00:00
-
时间换算单位
1秒 = 1000毫秒
Date类概述
Date 代表了一个特定的时间,精确到毫秒
public static void main(String[] args) throws ParseException {
/*
从1970年一月一日 开始
一秒等于1000毫秒
*/
Date date = new Date();
Date date1 = new Date(1000);
System.out.println("获取当前时间"+date1);
/*
常用的方法:
getTime():获取的是日期对象从1970年1月1日 00:00:00到现在的毫秒值
setTime(long time):设置时间,给的是毫秒值
toString(): 获取当前时间
toLocaleString():获取当前时间,但显示格式有所不同
*/
//获取现在的日期对象
String time = date.toLocaleString();
System.out.println(time+":");
//设置日期时间,毫秒值
date.setTime(1222455l);
}
SimpleDateFormat类的常用方法,格式化和解析日期
-
格式化(从Date到String)
- public final String format(Date date):将日期格式化成日期/时间字符串
-
解析(从String到Date)
- public Date parse(String source):从给定字符串的开始解析文本以生成日期
/*
SimpleDateFormat格式转换:
String format(Date date):将日期格式化成字符串
Date parse(String source):从给定字符串的开始解析文本以生成日期
*/
//将字符串格式化为时间
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String b = "2019-5-20 15:55:12";
Date parse = simpleDateFormat1.parse(b);
System.out.println("转换为时间格式:"+parse);
//将日期格式化成字符串
Date da = new Date();//获取当前时间
String a = simpleDateFormat1.format(da);
System.out.println("转换字符串格式:"+a);