如下是參考android系統源碼擷取統標準時區的時間,包括上下午的字串,例如設定系統日期格式為31-12-2012 ,那麼返回的字串就是31-12-2012上午
主要是同步系統日期的格式,並且瞭解android 中SimpeDataFormat 和 Data 的用法。
[java]
/**
* 獲得標準系統時間
* @param context
* @return
*/
public static String getDateAndTimeString(Context context) {
ContentResolver cv = context.getContentResolver();
Resources resources = context.getResources();
String timeString = null; www.2cto.com
String strDateFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.DATE_FORMAT);
if (TextUtils.isEmpty(strDateFormat)) {
strDateFormat = "yyyy-MM-dd";
}
SimpleDateFormat mmdateFormat = new SimpleDateFormat(strDateFormat);
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);
long dateTaken = System.currentTimeMillis();
int time[] = getHourAndMinuteOfDay(new Date(dateTaken), strTimeFormat);
timeString = resources.getString(Res.string.taken_on) + ": "
+ mmdateFormat.format(new Date(dateTaken)) + " " + time[ID_HOUR] + ":"
+ (time[ID_MINUTE] < 10 ? ("0" + time[ID_MINUTE]) : time[ID_MINUTE]);
if (time[ID_AM_PM] != -1) {
timeString = timeString.toString() + DateUtils.getAMPMString(time[ID_AM_PM]);
}
return timeString;
}
/**
* 獲得標準系統時間
* @param context
* @return
*/
public static String getDateAndTimeString(Context context) {
ContentResolver cv = context.getContentResolver();
Resources resources = context.getResources();
String timeString = null;
String strDateFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.DATE_FORMAT);
if (TextUtils.isEmpty(strDateFormat)) {
strDateFormat = "yyyy-MM-dd";
}
SimpleDateFormat mmdateFormat = new SimpleDateFormat(strDateFormat);
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);
long dateTaken = System.currentTimeMillis();
int time[] = getHourAndMinuteOfDay(new Date(dateTaken), strTimeFormat);
timeString = resources.getString(Res.string.taken_on) + ": "
+ mmdateFormat.format(new Date(dateTaken)) + " " + time[ID_HOUR] + ":"
+ (time[ID_MINUTE] < 10 ? ("0" + time[ID_MINUTE]) : time[ID_MINUTE]);
if (time[ID_AM_PM] != -1) {
timeString = timeString.toString() + DateUtils.getAMPMString(time[ID_AM_PM]);
}
return timeString;
}getHourAndMinuteOfDay(new Date(dateTaken), strTimeFormat)中的dateTaken可以是任意時間,所以此方法稍加改動,重用性還是很強的。