Java 搞個 datetime 計算真是很囉嗦, Oracle 簡潔多了. 更奇怪的是Java書都很少有詳盡的說明 Date/Calendar/Timestamp .
Date - java.util.Date
date001.getTime() - 取得 Date 毫秒數值 mSec since 1970/01/01
Calendar
cal001.getTime() - 取得 Calendar datetime 資料 since 1970/01/01
cal001.getTime().getTime() - 取得 Calendar 毫秒數值 mSec since 1970/01/01
Timestamp
java.sql.Timestamp dd001 = null;
Math:
Calendar cal01 = Calendar.getInstance(); // Declare Calendar object
cal01.setTime(someDate); // set Calendar object from date
cal01.add(Calendar.MINUTE, -90); // mathmatic add -90 minutes
cal01.add(Calendar.DATE, 1); // mathmatic add 1 day
java.util.Date d01 = cal01.getTime(); // Assign Calendar to Date object
java.util.Date date1 = new java.util.Date("12/15/2001");
java.util.Date date2 = new java.util.Date("10/30/2004");
long dayDiff = ((date2.getTime() - date1.getTime()) /86400000); //計算差異天數
Comparison (適用 Date & Calendar):
* if(cal01.after(cal02)) {} else {}
* if (dd001!=null) { } else { }
----- Use Groovy test -----
import java.text.*
import java.sql.*
println "Hello"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
java.util.Date dt = (java.util.Date) fmt.parse("2004/12/30 12:00:00");
Timestamp ts = new Timestamp(dt.getTime());
//println "dt= " "-"+fmt.format(dt)
//println "ts=" ts
//System.out.println(fmt.format(dt.getTime())); //java syntax
println fmt.format(dt.getTime())
----- Groovy Test 2 -----
import java.text.*;
import java.sql.Timestamp;
String str_date="2009-07-11"
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
java.util.Date date = (java.util.Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);
----- Groovy Test final -----
import java.util.* ; // ArrayList
import java.text.* ; // SimpleDateFormat
import java.sql.* //Timestamp
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date sysDate = new java.util.Date();
java.sql.Timestamp fmdate ; //= new java.sql.Timestamp ;
java.sql.Timestamp todate ; //= new java.sql.Timestamp ;
java.util.Date dt1 = (java.util.Date) sdf1.parse('2009/08/01')
java.util.Date dt2 = (java.util.Date) sdf1.parse('2009/08/02')
fmdate = new java.sql.Timestamp(dt1.getTime())
todate = new java.sql.Timestamp(dt2.getTime())
println('Date:'+sdf1.format(dt1) + '-' + sdf1.format(dt2))
println('Timestamp:'+sdf1.format(fmdate) +'-' + sdf1.format(todate))
沒有留言:
張貼留言