這兩天在做課設,關於圖書管理系統的,其中在借書的記錄中,時間記錄的月份總是出現不正常的數值,大於12經常四十幾五十幾,經過對借書模組的跟蹤,最後將錯誤定位到了時間格式化的這行代碼
SimpleDateFormat f = newSimpleDateFormat("yyyy-mm-dd HH:mm:ss");
經過這行代碼是要將格式化為常見的2013-07-11 09:07:20這種格式,結果經常出現2013-00-11 09:07:20或者2013-34-1109:07:20,月份很奇怪,然後發現yyyy-mm-ddHH:mm:ss中月份的MM被我小寫了,這導致在格式化時會把分鐘的時間放到月份位置,也就出現了奇怪的是月份,經過修改為
SimpleDateFormatf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
之後,時間就正常了.
雖然很簡單,但是提示我,再簡單的一行代碼也會有出錯的可能.
下面記錄一下SimpleDateFormat 的用法
Java 代碼:
import java.text.SimpleDateFormat;SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss ");Date curDate = new Date(System.currentTimeMillis());//擷取目前時間String str = formatter.format(curDate);
以上可以擷取當前的年月時分,也可以合起來寫(如下):
Java代碼:
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String date = sDateFormat.format(new java.util.Date());
如果想擷取當前的年月,則可以這樣寫(只擷取時間或者秒種用法一樣):
Java代碼:
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");String date=sdf.format(new java.util.Date());
當然還有就是可以指定時區的時間(待):
df=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,Locale.CHINA);System.out.println(df.format(new Date()));
如何擷取Android系統時間是24小時制還是12小時制:
ContentResolver cv = this.getContentResolver(); String strTimeFormat = android.provider.Settings.System.getString(cv, android.provider.Settings.System.TIME_12_24); if(strTimeFormat.equals("24")) { Log.i("activity","24"); }
取得系統日期:
Calendar c = Calendar.getInstance();year = c.get(Calendar.YEAR);month = c.grt(Calendar.MONTH);day = c.get(Calendar.DAY_OF_MONTH);hour = c.get(Calendar.HOUR_OF_DAY);minute = c.get(Calendar.MINUTE);
利用Time擷取:
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone資料。 t.setToNow(); // 取得系統時間。 int year = t.year; int month = t.month; int date = t.monthDay; int hour = t.hour; // 0-23 int minute = t.minute; int second = t.second;//唯一不足是取出時間只有24小時模式