package com.pb.demo3;import java.util.Calendar;import java.util.GregorianCalendar;/* * 使用Calendar類顯示當前時間, * 使用get方法表示時間,日期的各個部分數字如:年,月,日 * 使用set方法設置日期字段,將當前時間設置為9月 * 使用add方法為給定的日歷字段添加或者減去指定的時間量,在當前時間上加10天 * 使用GregorianCalendar的isLeapYear方法判斷是否是閏年 */public class CalendarDemo { public static void main(String[] args) { /* * 將當前日期時間表是為年,月,日,時,分,秒 */ Calendar calendar=Calendar.getInstance(); //日歷對象 int year=calendar.get(Calendar.YEAR); int month=calendar.get(Calendar.MONTH)+1; //月份默認是0-11需要手動加1 int day=calendar.get(Calendar.DAY_OF_MONTH); int hour=calendar.get(Calendar.HOUR_OF_DAY); int minute=calendar.get(Calendar.MINUTE); int second=calendar.get(Calendar.SECOND); System.out.三、SimpleDateFormat類格式化模板| No. | 標記 | 描述 |
| 1 | y | 年,年份是四位數字,所以需要使用“yyyy”表示年。 |
| 2 | M | 年中的月份,月份是兩位數字,所以需要使用“MM”表示月。 |
| 3 | d | 月中的天數,天數是兩位數字,所以需要使用“dd”表示日。 |
| 4 | H | 一天中的小時數(24小時),小時是兩位數字,使用“HH”表示小時。 |
| 5 | m | 小時中的分鐘數,分鐘是兩位數字,使用“mm”表示分鐘。 |
| 6 | s | 分鐘中的秒數,秒是兩位數字,使用“ss”表示秒。 |
| 7 | S | 毫秒數,毫秒數字是三位數字,使用“SSS”表示毫秒。 |
package com.pb.demo3;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateTest { public static void main(String[] args) { //聲明SimpleDateFormat對象并規定格式 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //獲得當前時間 Date date=new Date(); System.out.println("當前時間: "+sdf.format(date)); String newStr="2011-08-25 14:07:26"; try { Date newdate=sdf.parse(newStr); System.out.println("轉換后的時間:"+newdate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}新聞熱點
疑難解答