涉及的一些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 }
时间: 2024-10-18 14:08:00