Java 常用類Data和Format類 使用教程

一、Date類使用方法。

1. new Date() 返回當前時間
Date date = new Date();
System.out.println(date);//輸出當前的時間。

源碼解釋爲:
在這裏插入圖片描述

2. new Date(10006060*24); 返回 從 Fri Jan 01 08:00:00 CST 1970經過1天的時間
long time = 1000*60*60*24;
Date date = new Date(time);// Fri Jan 02 08:00:00 CST 1970

源碼解釋爲:
在這裏插入圖片描述

二 、DateFormat 格式化日期類

1. new DateFormat

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

字母意義:
y: 年year
M: 月Month
m : 分鐘minite
d : 天數day
H : 小時Hour
s : 秒 second
E : 星期幾 wEEk
a : 上下午 afternoon

2.format() 方法,格式化 毫秒–日期

format 可以將 到標準時間的毫秒數轉化爲 日期

dateFormat.format(new Date());//返回字符串 2020-04-24

3.parse() 反格式化‘(parse語法層次分析)

可以將標準格式化的日期轉化爲毫秒數

三、TimeZone 時區類 ,可以將時間轉化爲固定時區的時間.

1.創建時區類對象

TimeZone timeZone = TimeZone.getTimeZone("GMT+8");//北京時間
TimeZone timeZone = TimeZone.getTimeZone("GMT+8");//東京時間

2. 給格式化的日期設置時區

dateFormat.setTimeZone(timeZone);//

3.輸出設置好時區的格式化日期

System.out.println("北京時間爲: " + dateFormat.format(new Date()));
System.out.println("東京時間爲: " + dateFormat.format(new Date()));
//北京時間爲: 2020-04-24 
//東京時間爲: 2020-04-24 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章