在日常的开发中,我们常常需要根据各种需要,对日期进行不同形式的格式化。这里我将日常用到的日期格式化加以总结。写出个工具方法,欢迎大家总结:
1、对时间的加减操作,主要需求为闹钟等题型功能,用到的API为:Calendar
- /**
- * 获取增加多少月的时间
- *
- * @return addMonth - 增加多少月
- */
- public static Date getAddMonthDate(int addMonth) {
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.MONTH, addMonth);
- return calendar.getTime();
- }
- /**
- * 获取增加多少天的时间
- *
- * @return addDay - 增加多少天
- */
- public static Date getAddDayDate(int addDay) {
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.DAY_OF_YEAR, addDay);
- return calendar.getTime();
- }
- /**
- * 获取增加多少小时的时间
- *
- * @return addDay - 增加多少消失
- */
- public static Date getAddHourDate(int addHour) {
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.HOUR, addHour);
- return calendar.getTime();
- }
2、按照 yyyy/MM/dd hh:mm等格式显示日期,主要用到的API为:SimpleDateFormat,Time
- /**
- * 显示时间格式为 hh:mm
- *
- * @param context
- * @param when
- * @return String
- */
- @SuppressLint("SimpleDateFormat")
- public static String formatTimeShort(Context context, long when) {
- String formatStr = "HH:mm";
- SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
- String temp = sdf.format(when);
- if (temp != null && temp.length() == 5 && temp.substring(0, 1).equals("0")) {
- temp = temp.substring(1);
- }
- return temp;
- }
- /**
- * 显示时间格式为今天、昨天、yyyy/MM/dd hh:mm
- *
- * @param context
- * @param when
- * @return String
- */
- public static String formatTimeString(Context context, long when) {
- Time then = new Time();
- then.set(when);
- Time now = new Time();
- now.setToNow();
- String formatStr;
- if (then.year != now.year) {
- formatStr = "yyyy/MM/dd";
- } else if (then.yearDay != now.yearDay) {
- // If it is from a different day than today, show only the date.
- formatStr = "MM/dd";
- } else {
- // Otherwise, if the message is from today, show the time.
- formatStr = "HH:MM";
- }
- if (then.year == now.year && then.yearDay == now.yearDay) {
- return context.getString(R.string.date_today);
- } else if ((then.year == now.year) && ((now.yearDay - then.yearDay) == 1)) {
- return context.getString(R.string.date_yesterday);
- } else {
- SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
- String temp = sdf.format(when);
- if (temp != null && temp.length() == 5 && temp.substring(0, 1).equals("0")) {
- temp = temp.substring(1);
- }
- return temp;
- }
- }
DateUtils.formatDateTime(this, System.getTimeMillis(), DateUtils.FORMAT_SHOW_TIME);
5、判断两个日期是否是同一个日期:
- /**
- * 是否同一天
- *
- * @param date1
- * @param date2
- * @return
- */
- public static boolean isSameDate(long date1, long date2) {
- long days1 = date1 / (1000 * 60 * 60 * 24);
- long days2 = date2 / (1000 * 60 * 60 * 24);
- return days1 == days2;