本次内容:DateFormat类
1、DateFormat类
1 package array; 2 /** 3 * 时间和字符串之间的转化 4 */ 5 import java.text.DateFormat; 6 import java.text.ParseException; 7 import java.text.SimpleDateFormat; 8 import java.util.Date; 9 10 public class dateformat {11 public static void main(String[] args) throws ParseException12 {13 DateFormat d=new SimpleDateFormat("yyyy-MM-dd");14 Date t=new Date(123);15 String str=d.format(t);//将时间对象按照格式化字符串,转换成字符串16 System.out.println(str);17 System.out.println("###################");18 String str1="1977,7,7";19 DateFormat d1=new SimpleDateFormat("yyyy,MM,dd");//此处字符串格式必须和前面的字符串格式一致,或前面的字符串按此格式定义20 Date t1=d1.parse(str1);//将相应格式的字符串转换成时间21 System.out.println(t1);22 }23 }
运行结果:
1970-01-01###################Thu Jul 07 00:00:00 CST 19772、Calendar类
1 package array; 2 /** 3 * 此时日历类及日期计算 4 */ 5 import java.util.Calendar; 6 import java.util.Date; 7 import java.util.GregorianCalendar; 8 9 public class gregorian {10 public static void main(String[] args)11 {12 Calendar c=new GregorianCalendar();13 c.set(2001,1,1,12,12,12);14 Date d=c.getTime();15 System.out.println(d);16 System.out.println(c.getTime());17 System.out.println("###################");18 Calendar c1=new GregorianCalendar();19 c1.set(Calendar.YEAR, 2014);20 c1.set(Calendar.MONTH,5);21 c1.set(Calendar.DAY_OF_MONTH,1);22 System.out.println(c1.getTime());23 System.out.println(c1.get(Calendar.MONTH));24 System.out.println("###################");25 c1.add(Calendar.MONTH,1);//月份加126 System.out.println(c1.get(Calendar.MONTH));27 c1.add(Calendar.MONTH,-1);//月份减128 System.out.println(c1.get(Calendar.MONTH));29 }30 }
运行结果:
Thu Feb 01 12:12:12 CST 2001Thu Feb 01 12:12:12 CST 2001###################Sun Jun 01 10:56:52 CST 20145###################653、一个可视化日历练习:
1 package array; 2 3 import java.text.DateFormat; 4 import java.text.ParseException; 5 import java.text.SimpleDateFormat; 6 import java.util.Calendar; 7 import java.util.Date; 8 import java.util.GregorianCalendar; 9 import java.util.Scanner;10 11 12 public class visualcalendar {13 public static void main(String[] args) throws ParseException14 {15 System.out.println("请输入日期(格式为某年-某月-某日):");16 Scanner input=new Scanner(System.in);17 String str=input.nextLine();18 DateFormat df=new SimpleDateFormat("yyyy-MM-dd");19 Date d=df.parse(str); 20 Calendar c=new GregorianCalendar();21 c.setTime(d);22 int currentday=c.get(Calendar.DATE);23 c.set(Calendar.DATE, 1);24 System.out.println(c.get(Calendar.DAY_OF_WEEK));25 System.out.println(c.getActualMaximum(Calendar.DATE));26 System.out.println("日\t一\t二\t三\t四\t五\t六");27 int day=c.get(Calendar.DAY_OF_WEEK);28 int max=c.getActualMaximum(Calendar.DATE);29 int i,j;30 for(j=0;j<(day-1);j++)31 {32 System.out.print("\t");33 }34 for(i=1;i<=max;i++)35 {36 System.out.print(i);37 if(i==currentday)38 {39 System.out.print("*");40 }41 System.out.print('\t');42 int grade=c.get(Calendar.DAY_OF_WEEK);43 if(grade==Calendar.SATURDAY)44 System.out.println();45 c.add(Calendar.DATE, 1);46 }47 }48 }
运行结果: