java 中日期時間的整理
目錄
1>判斷是否是閏年:能被4整除且不能被100整除,或能被400整除為閏年
3、DateFormat類和SimpleDateFormat類
1、Date類
JDK1.8 原始碼,Date 類定義瞭解一下:
public class Date implements java.io.Serializable, Cloneable, Comparable<Date>{ private static final long serialVersionUID = 7523967970034938905L; private transient long fastTime; private static final BaseCalendar gcal = CalendarSystem.getGregorianCalendar(); public Date() { this(System.currentTimeMillis()); } public Date(long date) { fastTime = date; } }
建立一個時間物件有多個建構函式,目前 JDK1.8 僅推薦倆種:
Date date = new Date(); // 獲得一個 System.currentTimeMillis() 值
Date date = new Date(long date);
// long date 該整數的值代表的是距離格林尼治標準時間(1970年1月1日0時0分0秒)的毫秒數,
就是說fastTime值為1000的時候代表時間為1970年1月1日0時0分1秒。
2、Calendar類
現在關於日期使用最多的也就是該類,Calendar 要比Date強大很多,而且不需要考慮時區轉化問題。
JDK1.8 原始碼,Calendar 類定義瞭解一下:
public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
public final static int ERA = 0;
public final static int YEAR = 1;
public final static int MONTH = 2;
public final static int WEEK_OF_YEAR = 3;
public final static int WEEK_OF_MONTH = 4;
public final static int DATE = 5;
public final static int DAY_OF_MONTH = 5;
public final static int DAY_OF_YEAR = 6;
public final static int DAY_OF_WEEK = 7;
public final static int DAY_OF_WEEK_IN_MONTH = 8;
public final static int AM_PM = 9;
public final static int HOUR = 10;
public final static int HOUR_OF_DAY = 11;
public final static int MINUTE = 12;
public final static int SECOND = 13;
public final static int MILLISECOND = 14;
public final static int ZONE_OFFSET = 15;
public final static int DST_OFFSET = 16;
public final static int FIELD_COUNT = 17;
public final static int SUNDAY = 1;
public final static int MONDAY = 2;
public final static int TUESDAY = 3;
...
public final static int JANUARY = 0;
public final static int FEBRUARY = 1;
public final static int AM = 0;
public final static int PM = 1;
public static Calendar getInstance()
{
return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}
public static Calendar getInstance(TimeZone zone)
{
return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
}
}
上邊是原始碼中整理出來,可以看出 Calendar 類中有很多靜態變數,這些常量將會作為索引用來檢索 fields 屬性,例如:fields[YEAR]將返回當前毫秒值對應的日期時間的年份部分,fields[MONTH]將返回的是月份部分的值等等。
隨便呼叫我們的日期類,就可以看到其方法內部最後呼叫 internalGet 對 fields 值進行返回。
Calendar calendar = Calendar.getInstance(); calendar.set(year,month-1,day);
由原始碼常量定義可知:JANUARY = 0,FEBRUARY = 1...所以月份要 +1 才是當前月份;
上午=0,下午=1;
星期日=1,星期一=2,星期二=3,...
常用的一些方法:
1>判斷是否是閏年:能被4整除且不能被100整除,或能被400整除為閏年
@Test
public void isNotLeapYear(){
int year = 2018;
GregorianCalendar calendar = new GregorianCalendar();
System.out.println("判斷是否是閏年:"+calendar.isLeapYear(year));
}
2> 獲得今年有多少天
@Test
public void yearAllDay(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2018);
System.out.println("今年有多少天:"+cal.getActualMaximum(Calendar.DAY_OF_YEAR));
}
3>判斷今天是星期幾
@Test
public void whatWeek(){
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println("今天是星期幾:"+(c.get(Calendar.DAY_OF_WEEK)-1));//記得減一啊
}
4>獲取當前 年/月/周/日
@Test
public void dateYearMonthDay(){
Calendar calendar = Calendar.getInstance();
Date date = new Date();
//以下四個方法將廢棄,推薦下面的獲取方式
//int year = date.getYear()+1900;
//int month = date.getMonth();
//int week = date.getDay();
//int day = date.getDate();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int week = calendar.get(Calendar.DAY_OF_WEEK)-1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("year:"+year+"month:"+month+"week:"+week+"day:"+day);
}
5>獲取當月最大和最小的一天
@Test
public void dateMaxMinDay(){
Calendar calendar = Calendar.getInstance();
Date date = new Date();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, month, day);
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Max Day: " + maxDay);
int minDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
System.out.println("Min Day: " + minDay);
}
6>計算兩個日期之間相差的天數
@Test
public void daysBetween() throws ParseException {
Date startdate = new Date();
Date enddate = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
startdate=sdf.parse(sdf.format(startdate));
enddate=sdf.parse(sdf.format(enddate));
Calendar cal = Calendar.getInstance();
cal.setTime(startdate);
long time1 = cal.getTimeInMillis();
cal.setTime(enddate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
System.out.println("兩個日期之間相差的天數:"+Integer.parseInt(String.valueOf(between_days)));
}
7>距離當天日期 100 天的日期
@Test
public void dateAdd() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date parse = dateFormat.parse("20181126");
Calendar c =Calendar.getInstance();
c.setTime(parse);
c.add(Calendar.DATE, 100);//當前日期增加100天
//tempStart.add(Calendar.DAY_OF_YEAR, 1);//本年度的日數加一
String format = dateFormat.format(c.getTime());
System.out.println("距離當天日期 100 天的日期:"+format);
}
8>獲取某一日期區間的日期
@Test
public void dateGap() throws ParseException {
// 返回的日期集合
List<String> days = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date start = sdf.parse("2018-11-01");
Date end = sdf.parse("2018-11-23");
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);//本年度的日數加一
}
}
9>
10>
11>
3、DateFormat類和SimpleDateFormat類
JDK1.8 原始碼:DateFormat.class
public abstract class DateFormat extends Format {
private static final long serialVersionUID = 7218322306649953788L;
protected Calendar calendar;
protected NumberFormat numberFormat;
public static final int ERA_FIELD = 0;
...
}
JDK1.8 原始碼:SimpleDateFormat.class
public class SimpleDateFormat extends DateFormat {
static final long serialVersionUID = 4774881970558875024L;
static final int currentSerialVersion = 1;
private int serialVersionOnStream;
private String pattern;
...
}
這倆個類都是對日期時間進行格式化(如:可以將日期轉換為指定格式的文字,也可以將文字轉換為日期)
SimpleDateFormat 類是 DateFormat 類(抽象類)的子類 。可以實現自由定製格式型別。
建立 DateFormat 物件:
DateFormat df = DateFormat.getDateInstance() ;
df.format(DateFormat.YEAR_FIELD,new Locale("zh","CN")) ; // 格式化日期:Date -轉- String 2018年11月26日
df.parse("2018-11-26") // 格式化日期:String -轉- Date Mon Nov 26 00:00:00 CST 2018
建立 SimpleDateFormat 物件:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.format(new Date()) ; // 格式化日期:Date -轉- String 2018-11-26
sdf.parse("2018-11-26") ; // 格式化日期:String -轉- Date Mon Nov 26 00:00:00 CST 2018
4、日期類物件之間的互轉
以下內容是整理別人的部落格,忘記連結了,如有侵權請告知。
簡單測試類如下:
@Test
public void dateTransfer() throws ParseException {
/************************** Date 與 Calendar 互相轉換 begin ***************************************/
//1.Date 轉化為Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//2.Calenda轉換為Date
Calendar calendar2 = Calendar.getInstance();
Date date =calendar2.getTime();
/*************************** Date 與 Calendar 互相轉換 end **************************************/
/************************** String與 Date 互相轉換 begin ***************************************/
//1.Date 轉化String
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
String dateStr=sdf.format(new Date());
//2.String 轉化Date
String str="2010-5-27";
Date date2 = sdf.parse(str);
/*************************** String與 Date 互相轉換 end **************************************/
/************************** Calendar與 Date 互相轉換 begin ***************************************/
//1 .將Calendar物件轉換為Date(c.getTime())
Calendar c = Calendar.getInstance();
Date d = c.getTime();
// 2.將Date轉換為Calendar物件(s.setTime(date))
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
c1.setTime(d1);
/*************************** Calendar與 Date 互相轉換 end **************************************/
/************************** Calendar與Long互相轉換 begin ***************************************/
// 將Calendar物件轉換為相對時間
Calendar c2 = Calendar.getInstance();
long long1 = c2.getTimeInMillis();
System.out.println("將Calendar物件轉換為相對時間:"+long1);//1543244109740L
// 將long轉換為Calendar物件
Calendar cal = Calendar.getInstance();
long long2 = 1252785271098L;
cal.setTimeInMillis(long2);
System.out.println("將long轉換為Calendar物件:"+long2);//1252785271098
/*************************** Calendar與Long互相轉換 end **************************************/
/************************** Date與Long互相轉換 begin ***************************************/
//1.將Date類的物件轉換為long型時間
Date date3= new Date();
long longDate = date3.getTime();
System.out.println("將Date類的物件轉換為long型時間:"+longDate);//:1543243849147L
//2.將long型時間轉換為Date類的物件
long time = 1543243460536L;
Date dt = new Date(time);
System.out.println("使用Date的構造方法完成:"+dt);//Mon Nov 26 22:44:20 CST 2018
/*************************** Date與Long互相轉換 end **************************************/
}