项目中需要对时间进行大量的计算,比如说提前一个小时,推迟一个小时,推迟半个小时等,很多报表的数据都是从这里计算出来的。对于时间的计算是一个很大的问题,把一些常用的函数贴出来,大家一起研究下。 /** * 将时间推后一段时限 * * @param beginTime * String * @param hour * int * @return String */ public static String getAfterTime(String beginTime, int hour) { String temp = beginTime; int beginYear = Integer.parseInt(beginTime.substring(0, 4)); int beginMou = Integer.parseInt(beginTime.substring(5, 7)); int beginDay = Integer.parseInt(beginTime.substring(8, 10)); int beginHou = Integer.parseInt(beginTime.substring(11, 13)); int beginFen = Integer.parseInt(beginTime.substring(14, 16)); int beginSec = Integer.parseInt(beginTime.substring(17, 19)); beginHou = beginHou + hour; if (beginHou >= 24) { beginDay = beginDay + 1; beginHou = beginHou - 24; if (beginMou == 4 || beginMou == 6 || beginMou == 9 || beginMou == 11) { if (beginDay >= 30) { beginMou = beginMou + 1; beginDay = beginDay - 30; } } else if (beginMou == 1 || beginMou == 3 || beginMou == 5 || beginMou == 7 || beginMou == 8 || beginMou == 10 || beginMou == 12) { if (beginDay >= 31) { beginMou = beginMou + 1; beginDay = beginDay - 31; } } else if (beginMou == 2) { if (beginYear % 4 == 0) { if (beginDay >= 29) { beginMou = beginMou + 1; beginDay = beginDay - 29; } } else { if (beginDay >= 28) { beginMou = beginMou + 1; beginDay = beginDay - 28; } } } } if (beginMou > 12) { beginYear = beginYear + 1; beginMou = beginMou - 12; } temp = String.valueOf(beginYear) + "-" + String.valueOf(beginMou) + "-" + String.valueOf(beginDay) + " " + String.valueOf(beginHou) + ":" + String.valueOf(beginFen) + ":" + String.valueOf(beginSec); return temp; } //特定的时间加分钟,小时,天 public static String getLocalString1(String time,int disday, int hour, int min) throws ParseException { String ls_display = ""; Calendar cal = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cal.setTime(dateFormat.parse(time)); cal.add(Calendar.DATE, disday); cal.add(Calendar.HOUR, hour); cal.add(Calendar.MINUTE, min); String _yystr = "", _mmstr = "", _ddstr = "", _hourstr = "", _minstr = ""; int _yy = cal.get(Calendar.YEAR); _yystr = _yy + ""; int _mm = cal.get(Calendar.MONTH) + 1; _mmstr = _mm + ""; if (_mm < 10) { _mmstr = "0" + _mm; } int _dd = cal.get(Calendar.DATE); _ddstr = _dd + ""; if (_dd < 10) { _ddstr = "0" + _dd; } int _hh = cal.get(Calendar.HOUR_OF_DAY); if (_hh < 10) { _hourstr = "0" + _hh; } else { _hourstr = "" + _hh; } int _mi = cal.get(Calendar.MINUTE); if (_mi < 10) { _minstr = "0" + _mi; } else { _minstr = "" + _mi; } ls_display = _yy + "-" + _mmstr + "-" + _ddstr + " " + _hourstr + ":" + _minstr + ":00"; return ls_display; }
java对时间的操作函数
最新推荐文章于 2024-08-29 18:44:48 发布