android中時間 和 日期 格式化顯示
阿新 • • 發佈:2019-01-06
Android中時間 和 日期 格式化顯示:
【一】SimpleDateFormat 格式化程式碼------
// 輸出"年-月-日 時:分:秒 星期"
// 其中時間顯示是12小時制的,如果需要顯示24小時制,只需將hh換成kk
// 星期的表示 4個E是完全形式,一個E是縮寫
// 格式可以隨便改的
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss EEEE");
Calendar calendar = Calendar.getInstance();
// 返回這個calendar的Date物件
Date calendarDate = calendar.getTime();
// 已yyyy-MM-dd kk:mm:ss格式化calendarDate物件,並轉化成String物件
String time =simpleDateFormat.format(calendarDate );
public static String format24HourString(Context context, String time) { boolean is24Hour = DateFormat.is24HourFormat(context); Log.d("ljb", "time:" + time + ";is24Hour:" + is24Hour); String[] timeStrings = time.split(":"); if (timeStrings.length < 2) { return time; } if (!is24Hour) { String hourString = timeStrings[0]; String minString = timeStrings[1]; int hour = Integer.parseInt(hourString); if (hour > 12) { hour = hour - 12; return hour + ":" + minString + " " + context.getResources().getString(R.string.str_pm); } else if (hour == 12) { return hour + ":" + minString + " " + context.getResources().getString(R.string.str_pm); } else { return hour + ":" + minString + " " + context.getResources().getString(R.string.str_am); } } else { return time; } } public static String converHourFormat(Context context, String hour) { boolean is24hFormart = DateFormat.is24HourFormat(context); if (!is24hFormart) { String AmOrPm = context.getResources().getString(R.string.str_am); int hourTemp = Integer.parseInt(hour); if (hourTemp > 12) { AmOrPm = context.getResources().getString(R.string.str_pm); hourTemp -= 12; } else if (hourTemp == 12) { AmOrPm = context.getResources().getString(R.string.str_pm); } else { AmOrPm = context.getResources().getString(R.string.str_am); } return AmOrPm + " " + hourTemp; } else { return hour; } } public static String dateFormate(Context context, Time curTime) { String dateformat = SystemProperties.get("persist.sys.dateformat", "1"); if ("0".equals(dateformat)) { dateformat = "%m/%d/%Y"; } else if ("1".equals(dateformat)) { dateformat = "%d/%m/%Y"; } else { dateformat = "%Y/%m/%d"; } return curTime.format(dateformat); } public static String dateFormate(Context context, Date curDate) { String dateformat = SystemProperties.get("persist.sys.dateformat", "1"); if ("0".equals(dateformat)) { dateformat = "MM-dd-yyyy"; } else if ("1".equals(dateformat)) { dateformat = "dd-MM-yyyy"; } else { dateformat = "yyyy-MM-dd"; } return DateFormat.format(dateformat, curDate).toString(); }