import java.util.*; import java.text.SimpleDateFormat; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; public class TestDateTime { public static void main(String[] argv) { long nCurrentTime = System.currentTimeMillis(); java.util.Date utilDate = new java.util.Date(nCurrentTime); //以下是用于數(shù)據(jù)庫操作的日期和時間類 java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); //java.util.Date和java.sql.Date的轉(zhuǎn)換 java.sql.Time sqlTime = new java.sql.Time(utilDate.getTime()); java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(nCurrentTime); //Calendar用于獲取指定的時間項(字段) Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(nCurrentTime); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; //注意:返回的月份是基于0的! 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.println("Current date is: " + year + "年" + month + "月" + day + "日"); System.out.println("Current time is: " + hour + "時" + minute + "分" + second + "秒"); //SimpleDateFormat用于格式化日期和時間 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String szDatetime1 = df.format(utilDate); System.out.println("Current datetime is: " + szDatetime1); //以下計算兩個日期值之間相差的時間 java.util.Date date2 = new java.util.Date(nCurrentTime - 24600 * 1000); long nMilliSeconds = utilDate.getTime() - date2.getTime(); long nSeconds = nMilliSeconds / 1000; //把毫秒換算成秒 double nDays = nSeconds / (24d * 60d * 60d); //把秒換算成天 String szDatetime2 = df.format(date2); System.out.println("Time between " + szDatetime1 + " and " + szDatetime2 + " is " + nSeconds + " seconds (" + nDays + " days)"); } } 程序運行結(jié)果: C:\java>java TestDateTime Current date is: 2005年1月2日 Current time is: 15時55分45秒 Current datetime is: 2005-01-02 15:55:45 Time between 2005-01-02 15:55:45 and 2005-01-02 09:05:45 is 24600 seconds (0.2847222222222222 days) |
|