在groovy中我有以下代碼來獲取當前時間(以小時爲單位)。在groovy/java中獲取當前時間
def now = new Date()
def time = now.getHours()
但getHour()方法已被棄用。如果我使用這個方法有什麼缺點,在groovy/Java中有什麼替代方法?
在groovy中我有以下代碼來獲取當前時間(以小時爲單位)。在groovy/java中獲取當前時間
def now = new Date()
def time = now.getHours()
但getHour()方法已被棄用。如果我使用這個方法有什麼缺點,在groovy/Java中有什麼替代方法?
使用Calendar
,
Calendar cal=Calendar.getInstance();//it return same time as new Date()
def hour = cal.get(Calendar.HOUR_OF_DAY)
有關詳細信息,請閱讀本docs。
可以使用喬達時間用於獲取當前時間或調用getHours
嘗試使用Joda Time而不是標準java.util.Date類。喬達時間庫有更好的API來處理日期。
DateTime dt = new DateTime(); // current time
int month = dt.getMonth(); // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day
您可以使用像這樣的傳統類來從給定的Date實例中獲取字段。
Date date = new Date(); // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR); // gets hour in 12h format
calendar.get(Calendar.MONTH); // gets month number, NOTE this is zero based!
它會告訴你用什麼[文檔中](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getHours%28%29) –
[Java:getMinutes和getHours]的可能重複(http://stackoverflow.com/questions/907170/java-getminutes-and-gethours) –
也http://stackoverflow.com/questions/8150155/java-gethours- getminutes-and-getseconds和http://stackoverflow.com/questions/13343524/the-correct-way-to-set-and-get-hour-minutes-sec –