【java】Date与String之间的转换及Calendar类:java.text.SimpleDateFormat、public Date parse(String source) throws ParseException和public final String format(Date date)

时间:2021-12-11 17:19:44
 package 日期日历类;

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; public class TestDate {
public static void main(String[] args) {
Date date=new java.util.Date();
System.out.println(date);//Fri Apr 07 22:20:12 CST 2017
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d=sdf.format(date);
System.out.println(d);//2017-04-07 22:20:12
String d2="2017-04-06 12:30:30";
Date date2=new Date();
try {
date2 = sdf.parse(d2);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date2);//Thu Apr 06 12:30:30 CST 2017
}
}

java.lang.Object
  java.text.Format
    java.text.DateFormat ->public Date parse(String source) throws ParseException和public final String format(Date date)
      java.text.SimpleDateFormat


 package 日期日历类;

 import java.util.Calendar;
import java.util.Date; public class TestDate {
public static void main(String[] args) {
Date date=new java.util.Date();
System.out.println(date);//Fri Apr 07 22:53:21 CST 2017
Calendar cal=Calendar.getInstance();
System.out.println(cal);//java.util.GregorianCalendar[time=1491576801409,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=3,WEEK_OF_YEAR=14,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=97,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=53,SECOND=21,MILLISECOND=409,ZONE_OFFSET=28800000,DST_OFFSET=0]
Date date2=cal.getTime();//Calendar转为Date
System.out.println(date2);//Fri Apr 07 22:53:21 CST 2017
StringBuffer sb=new StringBuffer(); //月份从0开始算,所以要加1
sb.append(cal.get(Calendar.YEAR)).append("年").append(cal.get(Calendar.MONTH)+1).append("月").append(cal.get(Calendar.DAY_OF_MONTH)).append("日").append(cal.get(Calendar.HOUR_OF_DAY)).append(":").append(cal.get(Calendar.MINUTE)).append(":").append(cal.get(Calendar.SECOND));
System.out.println(sb);//2017年4月7日22:53:21
}
}