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); //以下是用于数据库操作的日期和时间类 java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); //java.util.Date和java.sql.Date的转换 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)"); } } 程序运行结果: 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) |