1. 程式人生 > >java筆記------日期API

java筆記------日期API

package bsp see mini ngs time edate 構造方法 area

涉及的一些api:

Calendar calendar = Calendar.getInstance();

calendar.getTime();
calendar.setTime(date);
calendar.set(Calendar.YEAR,2000);
calendar.get(Calendar.DATE);
calendar.add(Calendar.DAY_OF_YEAR, 10);
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar1.after(calendar2);
calendar.getTimeInMillis();

SimpleDateFormat sdf = new SimpleDateFormat();

sdf.parse();
sdf.format();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");

String strTime = sdf.format(date);

date = sdf.parse(strTime);

舉例及說明如下代碼:

 1 package test;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Calendar;
6 import java.util.Date; 7 8 public class DateDemo { 9 10 public static void main(String[] args) throws ParseException { 11 Date date = new Date(); 12 13 //當前時間毫秒值,long類型 14 long numTime = date.getTime(); 15 System.out.println(numTime); 16 17 //
以"yyyy-MM-dd HH:mm:ss E" 格式 構造SimpleDateFormat的對象 18 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E"); 19 20 // 根據Date類型對象 生成sdf中的格式(構造方法中指定了)的字符串時間 21 String strTime = sdf.format(date); 22 System.out.println(strTime); 23 24 //從字符串strTime 以sdf中的格式(構造方法中指定了) 生成 Date類型對象 25 date = sdf.parse(strTime); 26 System.out.println(date); 27 28 //Calendar是抽象類,不能直接new生成 29 Calendar calendar = Calendar.getInstance(); 30 Calendar calendar2 = calendar; 31 System.out.println(calendar);//直接這樣輸出的看不懂,java.util.GregorianCalendar[time=1504450592066,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=8,WEEK_OF_YEAR=36,WEEK_OF_MONTH=2,DAY_OF_MONTH=3,DAY_OF_YEAR=246,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=56,SECOND=32,MILLISECOND=66,ZONE_OFFSET=28800000,DST_OFFSET=0] 32 33 //獲得date對象 34 date = calendar.getTime(); 35 36 //將date中時間設置給calendar 37 calendar.setTime(date); 38 39 //獲取 40 calendar.get(Calendar.YEAR); 41 42 //設置 43 calendar.set(Calendar.MONTH, 0); 44 45 //增加 46 calendar.add(Calendar.DAY_OF_YEAR, 10); 47 48 //指定日歷字段可能擁有的最大值。在此句中指當前月份的最大天數。 49 calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 50 51 52 53 //boolean類型,判斷calendar1的時間是否在calendar2之後 54 calendar.after(calendar2); 55 56 //獲得毫秒值,返回long類型 57 calendar.getTimeInMillis(); 58 59 60 } 61 62 }

java筆記------日期API