获取时间、格式化时间、时间加减
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Test {
public static void main(String[] args) throws Exception {
/**
* Date类:获得当前时间距格林尼治时间偏移量 Date()
* 或者由距格林尼治时间偏移量的毫秒数指定某一时间 Date(long time)
*/
Date dateNow = new Date();
Date dateMy = new Date(1000000000000l);
System.out.println(dateNow);
System.out.println(dateMy);
/**
* SimpleDateFormat:格式化日期
* G Era 标志符 Text AD
y 年 Year 1996; 96
M 年中的月份 Month July; Jul; 07
w 年中的周数 Number 27
W 月份中的周数 Number 2
D 年中的天数 Number 189
d 月份中的天数 Number 10
F 月份中的星期 Number 2
E 星期中的天数 Text Tuesday; Tue
a Am/pm 标记 Text PM
H 一天中的小时数(0-23) Number 0
k 一天中的小时数(1-24) Number 24
K am/pm 中的小时数(0-11) Number 0
h am/pm 中的小时数(1-12) Number 12
m 小时中的分钟数 Number 30
s 分钟中的秒数 Number 55
S 毫秒数 Number 978
z 时区 General time zone Pacific Standard Time; PST; GMT-08:00
Z 时区 RFC 822 time zone -0800
*/
//Date格式化成字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd, F-EE");
String formatNow = sdf.format(dateNow);
System.out.println(formatNow);
//字符串解析成Date
Date parse = sdf.parse(formatNow);
System.out.println(parse);
/**
* Calendar:对日期进行操作的抽象类;常用的实现子类:GregorianCalendar
* 字段 默认值 备注
* ERA AD
YEAR 1970 真实年份
MONTH JANUARY 1月是0
DAY_OF_MONTH 1 1号是1
DAY_OF_WEEK 一个星期的第一天 周日是第1天
WEEK_OF_MONTH 0 第1周是1
DAY_OF_WEEK_IN_MONTH 1
AM_PM AM
HOUR, HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND 0
*/
Calendar now = new GregorianCalendar();
now.setTimeInMillis(System.currentTimeMillis());
int year = now.get(Calendar.YEAR);
int mouth = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
System.out.println(year + " " + mouth + " " + day);
//时间加减
now.add(Calendar.YEAR, 1);
now.add(Calendar.MONTH, -1);
now.add(Calendar.DAY_OF_MONTH, 2);
System.out.println(now.get(Calendar.YEAR) + " " + now.get(Calendar.MONTH) + " " + now.get(Calendar.DAY_OF_MONTH));
/**
* Console
* Thu Oct 04 12:00:40 CST 2018
Sun Sep 09 09:46:40 CST 2001
2018-10-04, 1-星期四
Thu Oct 04 00:00:00 CST 2018
2018 9 4
2019 8 6
*/
}
}