日期和String之间的转换(待续)

tech2025-01-13  9

一、获取当前的年月日时分秒可以使用Calendar日历类

public static void main(String[] args) { //时间的格式化 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); //当前系统时间 Date date = cal.getTime(); String nowTime = sdf.format(cal.getTime()); //输出 当前的系统时间 System.out.println(nowTime); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); //中国的月份比标准的大于,因为中国的是从1开始算的 int month = calendar.get(Calendar.MONTH); int hour2 = calendar.get(Calendar.HOUR_OF_DAY); int week = calendar.get(Calendar.DAY_OF_WEEK); System.out.println(month+" "+ hour2+" " + week); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.DAY_OF_YEAR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); int millisecond = calendar.get(Calendar.MILLISECOND); System.out.println(year + " " + month + " " + day+ " "+ hour+" "+minute+" "+ second+ " "+millisecond); }

二、常用的日期操作

/** * 获得next天之后的日期 * @param next * @return */ public static Date getNextDate(int next){ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, next); return calendar.getTime(); } /** * 计算两个时间相差的天数 * @param beginTime * @param endTime * @return */ public static int days(Date beginTime, Date endTime){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("DDD"); Integer beginDays = Integer.parseInt(simpleDateFormat.format(beginTime)); Integer endDays = Integer.parseInt(simpleDateFormat.format(endTime)); return endDays - beginDays; } /** * 日期对象转换成指定格式的字符串 * @param date * @param pattern * @return */ public static String date2Str(Date date, String pattern){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); return simpleDateFormat.format(date); }
最新回复(0)