JavaやOracle SQLを使っていて、いつも不満に思うのが、String 型で”2010-12-25″と書いたときに、DateクラスやTimestampクラスに簡単に変換できないことです。
Javaでは、日付を扱うのにCalendarクラスを使うことを推奨しながら、DateクラスやTimestampクラスに変換するのにもやっかいなことです。
指定された日付・時刻文字列を、可能な限りCalendarクラスに変換します。
以下の形式の日付文字列を変換できます。
●変換可能な形式は以下となります。
* yyyy/MM/dd
* yy/MM/dd
* yyyy-MM-dd
* yyyyMMdd
* yy-MM-dd この形式は0から29までが2000年代となり、30から99年までが1900年代となります。
* yyMMdd
日付に以下の時間フィールドが組み合わされた状態でも有効です。
* HH:mm
* HHmm
* HH:mm:ss
* HHmmss
* HH:mm:ss.SSS
* HHmmssSSS
@param strDate 日付・時刻文字列。
@return 変換後のCalendarクラス。
@throws IllegalArgumentException
日付文字列が変換不可能な場合。または、矛盾している場合(例:2000/99/99)。
/* * SeeDo * eWave Solutions Inc.(c) 2000-2011, LAMP/EPFL */ package seedo import java.sql.{Timestamp,Date} import java.util.Calendar object Util { def toCalendar(_strDate:String) :Calendar ={ var strDate:String = format(_strDate) val cal = Calendar.getInstance cal.setLenient(false) var yyyy = Integer.parseInt(strDate.substring(0,4)) var MM = Integer.parseInt(strDate.substring(5,7)) var dd = Integer.parseInt(strDate.substring(8,10)) var HH = cal.get(Calendar.HOUR_OF_DAY) var mm = cal.get(Calendar.MINUTE) var ss = cal.get(Calendar.SECOND) var SSS = cal.get(Calendar.MILLISECOND) cal.clear cal.set(yyyy,MM-1,dd) if(strDate.length == 10) { ; }else if(strDate.length == 16){// yyyy/MM/dd HH:mm HH = Integer.parseInt(strDate.substring(11,13)) mm = Integer.parseInt(strDate.substring(14,16)) cal.set(Calendar.HOUR_OF_DAY,HH) cal.set(Calendar.MINUTE,mm) }else if(strDate.length == 19){//yyyy/MM/dd HH:mm:ss HH = Integer.parseInt(strDate.substring(11,13)) mm = Integer.parseInt(strDate.substring(14,16)) ss = Integer.parseInt(strDate.substring(17,19)) cal.set(Calendar.HOUR_OF_DAY,HH); cal.set(Calendar.MINUTE,mm); cal.set(Calendar.SECOND,ss); }else if(strDate.length == 23){//yyyy/MM/dd HH:mm:ss.SSS HH = Integer.parseInt(strDate.substring(11,13)) mm = Integer.parseInt(strDate.substring(14,16)) ss = Integer.parseInt(strDate.substring(17,19)) SSS = Integer.parseInt(strDate.substring(20,23)) cal.set(Calendar.HOUR_OF_DAY,HH) cal.set(Calendar.MINUTE,mm) cal.set(Calendar.SECOND,ss) cal.set(Calendar.MILLISECOND,SSS) }else{ throw new IllegalArgumentException("Can not change from ["+ strDate + "] to Date String") } cal } def toDate(strDate:String) :java.sql.Date = { val c = toCalendar(strDate) new java.sql.Date(c.getTimeInMillis) } def toTimestamp(strDate:String) :java.sql.Timestamp = { val c = toCalendar(strDate); new java.sql.Timestamp(c.getTimeInMillis); } }
コメントを残す
コメントを投稿するにはログインしてください。