关于Java日期工具类的编写
作者:wespten
这篇文章主要介绍了关于Java日期工具类的编写,在Java开发中,经常会遇到处理日期相关的数据,那么今天我们来自己写一个工具类,文中有详细的实例代码以及实现思路,需要的朋友可以参考下
Java日期工具类编写
将字符串转换为对应日期
Date date = simpleDateFormat.parse(string);
将日期转换为字符串
String string = simpleDateFormat.format(date);
注意,因为可能定义的格式和实际字符串提供的格式不符合,所以会抛出异常。
将年月日的汉字日期转为 - - 分隔符的日期
public static void main(String[] args) throws ParseException { //统一日期格式 String StrVal = "2018年05月22日"; Date d1 = new SimpleDateFormat("yyyy年MM月dd日").parse(StrVal); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String time = format.format(d1); System.out.println(time); }
/** * 将日期对象格式化为指定格式的日期字符串 * @param date 传入的日期对象 * @param format 格式 * @return */ public static String formatDate(Date date,String format){ String result=""; SimpleDateFormat sdf=new SimpleDateFormat(format); if(date!=null){ result=sdf.format(date); } return result; } /** * 将日期字符串转换成一个日期对象 * @param dateStr 日期字符串 * @param format 格式 * @return * @throws ParseException */ public static Date formatDate(String dateStr,String format) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat(format); return sdf.parse(dateStr); } public static void main(String[] args) throws ParseException { Date date=new Date(); System.out.println(formatDate(date,"yyyy-MM-dd")); System.out.println(formatDate(date,"yyyy-MM-dd HH:mm:ss")); System.out.println(formatDate(date,"yyyy年MM月dd日HH时mm分ss秒")); String dataStr="1989-11-02 18:01:41"; Date date2=formatDate(dataStr,"yyyy-MM-dd HH:mm:ss"); System.out.println(formatDate(date2,"yyyy-MM-dd HH:mm:ss")); }
运行输出:
2016-11-02
2016-11-02 18:06:50
2016年11月02日18时06分50秒
1989-11-02 18:01:41
SimpleDateFormat类主要是用作日期类型转换用的,常用的日期格式化
public static void main(String[] args) { //默认输出格式 Date date=new Date(); System.out.println(date); //日期格式化显示,首先定义格式 SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf4=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"); //将格式应用于日期 System.out.println(sdf1.format(date)); System.out.println(sdf2.format(date)); System.out.println(sdf3.format(date)); System.out.println(sdf4.format(date)); }
JavaCalendar日历类的时间操作
Calendar有个DAY_OF_WEEK 可以返回一个星期中的第几天;
这里说下注意点 老外的第一天是从星期日开始的,所以要-1;
import java.util.Calendar; public class Test { public static void main(String[] args) { String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; Calendar calendar=Calendar.getInstance(); System.out.println("今天是"+weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1]); } }
对日历进行操作
public static void main(String[] args) { //默认输出格式 Date now = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String time = format.format(now); System.out.println(time); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.MONTH, 1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String nowTime = sdf.format(calendar.getTime()); System.out.println(nowTime); calendar.add(Calendar.MONTH, -2); String nowTime2 = sdf.format(calendar.getTime()); System.out.println(nowTime2); }
获取时间
赋值时年月日时分秒常用的6个值,注意月份下标从0开始,所以取月份要+1
public static void main(String[] args) { //默认输出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(nowSdf.format(now)); Calendar calendar = Calendar.getInstance(); // 赋值时年月日时分秒常用的6个值,注意月份下标从0开始,所以取月份要+1 System.out.println("年:" + calendar.get(Calendar.YEAR)); System.out.println("月:" + (calendar.get(Calendar.MONTH) + 1)); System.out.println("日:" + calendar.get(Calendar.DAY_OF_MONTH)); System.out.println("时:" + calendar.get(Calendar.HOUR_OF_DAY)); System.out.println("分:" + calendar.get(Calendar.MINUTE)); System.out.println("秒:" + calendar.get(Calendar.SECOND)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String nowTime2 = sdf.format(calendar.getTime()); System.out.println(nowTime2); }
设置时间
如果想设置为某个日期,可以一次设置年月日时分秒,由于月份下标从0开始赋值月份要-1
public static void main(String[] args) { //默认输出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(nowSdf.format(now)); Calendar calendar = Calendar.getInstance(); calendar.set(2013, 5, 4, 13, 44, 51); calendar.set(Calendar.YEAR, 2014);//年 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime = sdf.format(calendar.getTime()); System.out.println(nowTime); calendar.set(Calendar.MONTH, 7);//月(月份0代表1月) SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime1 = sdf1.format(calendar.getTime()); System.out.println(nowTime1); calendar.set(Calendar.DATE, 11);//日 calendar.set(Calendar.HOUR_OF_DAY, 15);//时 calendar.set(Calendar.MINUTE, 33);//分 calendar.set(Calendar.SECOND, 32);//秒 }
时间计算
public static void main(String[] args) { //默认输出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(nowSdf.format(now)); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.YEAR, 1);//年 calendar.add(Calendar.MONTH, 1);//月 calendar.add(Calendar.DATE, 1);//日 //calendar.add(Calendar.DAY_OF_YEAR, 1);//今年的第 N 天 //calendar.add(Calendar.DAY_OF_MONTH, 1); // 本月第 N 天 //calendar.add(Calendar.DAY_OF_WEEK, 1);// 本周几 calendar.add(Calendar.HOUR_OF_DAY, -1);//时 calendar.add(Calendar.MINUTE, 1);//分 calendar.add(Calendar.SECOND, 1);//秒 //calendar.add(calendar.WEEK_OF_MONTH, 1);//增加一个礼拜 //calendar.add(calendar.WEEK_OF_YEAR,1);//增加一个礼拜 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime1 = sdf1.format(calendar.getTime()); System.out.println(nowTime1); }
日期的计算
获取本月最小天数与最大天数
public static void main(String[] args) { //默认输出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); int firstD = calendar.getActualMinimum(calendar.DAY_OF_MONTH); int lastD = calendar.getActualMaximum(calendar.DAY_OF_MONTH); System.out.println("获取本月的第一天和最后天:" + firstD +"," + lastD); }
获取本周星期一、上周星期一、这周星期一
public static Date geLastWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(getThisWeekMonday(date)); cal.add(Calendar.DATE, -7); return cal.getTime(); } public static Date getThisWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); // 获得当前日期是一个星期的第几天 int dayWeek = cal.get(Calendar.DAY_OF_WEEK); if (1 == dayWeek) { cal.add(Calendar.DAY_OF_MONTH, -1); } // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一 cal.setFirstDayOfWeek(Calendar.MONDAY); // 获得当前日期是一个星期的第几天 int day = cal.get(Calendar.DAY_OF_WEEK); // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值 cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day); return cal.getTime(); } public static Date getNextWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(getThisWeekMonday(date)); cal.add(Calendar.DATE, 7); return cal.getTime(); } public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = sdf.parse("2017-09-10"); System.out.println("今天是" + sdf.format(date)); System.out.println("上周一" + sdf.format(geLastWeekMonday(date))); System.out.println("本周一" + sdf.format(getThisWeekMonday(date))); System.out.println("下周一" + sdf.format(getNextWeekMonday(date))); } catch (Exception e) { e.printStackTrace(); } }
天数计算
用Date类计算日期差
public static void main(String[] args) { Calendar love = Calendar.getInstance(); Calendar now = Calendar.getInstance(); love.set(2016, 8, 6); //真实的日期是2016-9-6; int days = (int) ((now.getTimeInMillis() - love.getTimeInMillis()) / (24 * 60 * 60 * 1000.0)); System.out.println(days); }
public static void main(String[] args) throws ParseException { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");//大小写还是很重要的 Date LoveDay=new Date(); Date now=new Date(); LoveDay=format.parse("2016-08-06"); int day=(int) ((now.getTime()-LoveDay.getTime())/(24*60*60*1000)); System.out.println(day); }
日期工具类
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils { public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final String MINUTE_PATTERN = "yyyy-MM-dd HH:mm"; public static final String HOUR_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_PATTERN = "yyyy-MM-dd"; public static final String MONTH_PATTERN = "yyyy-MM"; public static final String YEAR_PATTERN = "yyyy"; public static final String MINUTE_ONLY_PATTERN = "mm"; public static final String HOUR_ONLY_PATTERN = "HH"; /** * 日期相加减天数 * @param date 如果为Null,则为当前时间 * @param days 加减天数 * @param includeTime 是否包括时分秒,true表示包含 * @return * @throws ParseException */ public static Date dateAdd(Date date, int days, boolean includeTime) throws ParseException{ if(date == null){ date = new Date(); } if(!includeTime){ SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_PATTERN); date = sdf.parse(sdf.format(date)); } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); return cal.getTime(); } /** * 时间格式化成字符串 * @param date Date * @param pattern StrUtils.DATE_TIME_PATTERN || StrUtils.DATE_PATTERN, 如果为空,则为yyyy-MM-dd * @return * @throws ParseException */ public static String dateFormat(Date date, String pattern) throws ParseException{ if(pattern==null||pattern.length()==0||pattern.equals(" ")){ pattern = DateUtils.DATE_PATTERN; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(date); } /** * 字符串解析成时间对象 * @param dateTimeString String * @param pattern StrUtils.DATE_TIME_PATTERN || StrUtils.DATE_PATTERN,如果为空,则为yyyy-MM-dd * @return * @throws ParseException */ public static Date dateParse(String dateTimeString, String pattern) throws ParseException{ if(pattern==null||pattern.length()==0||pattern.equals(" ")){ pattern = DateUtils.DATE_PATTERN; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.parse(dateTimeString); } /** * 将日期时间格式成只有日期的字符串(可以直接使用dateFormat,Pattern为Null进行格式化) * @param dateTime Date * @return * @throws ParseException */ public static String dateTimeToDateString(Date dateTime) throws ParseException{ String dateTimeString = DateUtils.dateFormat(dateTime, DateUtils.DATE_TIME_PATTERN); return dateTimeString.substring(0, 10); } /** * 当时、分、秒为00:00:00时,将日期时间格式成只有日期的字符串, * 当时、分、秒不为00:00:00时,直接返回 * @param dateTime Date * @return * @throws ParseException */ public static String dateTimeToDateStringIfTimeEndZero(Date dateTime) throws ParseException{ String dateTimeString = DateUtils.dateFormat(dateTime, DateUtils.DATE_TIME_PATTERN); if(dateTimeString.endsWith("00:00:00")){ return dateTimeString.substring(0, 10); }else{ return dateTimeString; } } /** * 将日期时间格式成日期对象,和dateParse互用 * @param dateTime Date * @return Date * @throws ParseException */ public static Date dateTimeToDate(Date dateTime) throws ParseException{ Calendar cal = Calendar.getInstance(); cal.setTime(dateTime); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * 时间加减小时 * @param startDate 要处理的时间,Null则为当前时间 * @param hours 加减的小时 * @return Date */ public static Date dateAddHours(Date startDate, int hours) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.HOUR, c.get(Calendar.HOUR) + hours); return c.getTime(); } /** * 时间加减分钟 * @param startDate 要处理的时间,Null则为当前时间 * @param minutes 加减的分钟 * @return */ public static Date dateAddMinutes(Date startDate, int minutes) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + minutes); return c.getTime(); } /** * 时间加减秒数 * @param startDate 要处理的时间,Null则为当前时间 * @param minutes 加减的秒数 * @return */ public static Date dateAddSeconds(Date startDate, int seconds) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.SECOND, c.get(Calendar.SECOND) + seconds); return c.getTime(); } /** * 时间加减天数 * @param startDate 要处理的时间,Null则为当前时间 * @param days 加减的天数 * @return Date */ public static Date dateAddDays(Date startDate, int days) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.DATE, c.get(Calendar.DATE) + days); return c.getTime(); } /** * 时间加减月数 * @param startDate 要处理的时间,Null则为当前时间 * @param months 加减的月数 * @return Date */ public static Date dateAddMonths(Date startDate, int months) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.MONTH, c.get(Calendar.MONTH) + months); return c.getTime(); } /** * 时间加减年数 * @param startDate 要处理的时间,Null则为当前时间 * @param years 加减的年数 * @return Date */ public static Date dateAddYears(Date startDate, int years) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.YEAR, c.get(Calendar.YEAR) + years); return c.getTime(); } /** * 时间比较(如果myDate>compareDate返回1,<返回-1,相等返回0) * @param myDate 时间 * @param compareDate 要比较的时间 * @return int */ public static int dateCompare(Date myDate, Date compareDate) { Calendar myCal = Calendar.getInstance(); Calendar compareCal = Calendar.getInstance(); myCal.setTime(myDate); compareCal.setTime(compareDate); return myCal.compareTo(compareCal); } /** * 获取两个时间中最小的一个时间 * @param date * @param compareDate * @return */ public static Date dateMin(Date date, Date compareDate) { if(date == null){ return compareDate; } if(compareDate == null){ return date; } if(1 == dateCompare(date, compareDate)){ return compareDate; }else if(-1 == dateCompare(date, compareDate)){ return date; } return date; } /** * 获取两个时间中最大的一个时间 * @param date * @param compareDate * @return */ public static Date dateMax(Date date, Date compareDate) { if(date == null){ return compareDate; } if(compareDate == null){ return date; } if(1 == dateCompare(date, compareDate)){ return date; }else if(-1 == dateCompare(date, compareDate)){ return compareDate; } return date; } /** * 获取两个日期(不含时分秒)相差的天数,不包含今天 * @param startDate * @param endDate * @return * @throws ParseException */ public static int dateBetween(Date startDate, Date endDate) throws ParseException { Date dateStart = dateParse(dateFormat(startDate, DATE_PATTERN), DATE_PATTERN); Date dateEnd = dateParse(dateFormat(endDate, DATE_PATTERN), DATE_PATTERN); return (int) ((dateEnd.getTime() - dateStart.getTime())/1000/60/60/24); } /** * 获取两个日期(不含时分秒)相差的天数,包含今天 * @param startDate * @param endDate * @return * @throws ParseException */ public static int dateBetweenIncludeToday(Date startDate, Date endDate) throws ParseException { return dateBetween(startDate, endDate) + 1; } /** * 获取日期时间的年份,如2017-02-13,返回2017 * @param date * @return */ public static int getYear(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); } /** * 获取日期时间的月份,如2017年2月13日,返回2 * @param date * @return */ public static int getMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.MONTH) + 1; } /** * 获取日期时间的第几天(即返回日期的dd),如2017-02-13,返回13 * @param date * @return */ public static int getDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DATE); } /** * 获取日期时间当月的总天数,如2017-02-13,返回28 * @param date * @return */ public static int getDaysOfMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.getActualMaximum(Calendar.DATE); } /** * 获取日期时间当年的总天数,如2017-02-13,返回2017年的总天数 * @param date * @return */ public static int getDaysOfYear(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.getActualMaximum(Calendar.DAY_OF_YEAR); } /** * 根据时间获取当月最大的日期 * <li>2017-02-13,返回2017-02-28</li> * <li>2016-02-13,返回2016-02-29</li> * <li>2016-01-11,返回2016-01-31</li> * @param date Date * @return * @throws Exception */ public static Date maxDateOfMonth(Date date) throws Exception { Calendar cal = Calendar.getInstance(); cal.setTime(date); int value = cal.getActualMaximum(Calendar.DATE); return dateParse(dateFormat(date, MONTH_PATTERN) + "-" + value, null); } /** * 根据时间获取当月最小的日期,也就是返回当月的1号日期对象 * @param date Date * @return * @throws Exception */ public static Date minDateOfMonth(Date date) throws Exception { Calendar cal = Calendar.getInstance(); cal.setTime(date); int value = cal.getActualMinimum(Calendar.DATE); return dateParse(dateFormat(date, MONTH_PATTERN) + "-" + value, null); } }
public static void main(String[] args) throws Exception { System.out.println(dateTimeToDate(new Date())); System.out.println(dateParse("2017-02-04 14:58:20", null)); System.out.println(dateTimeToDateStringIfTimeEndZero(new Date())); System.out.println(dateTimeToDateStringIfTimeEndZero(dateTimeToDate(new Date()))); System.out.println(dateBetween(dateParse("2017-01-30", null), dateParse("2017-02-01", null))); System.out.println(dateBetweenIncludeToday(dateParse("2017-01-30", null), dateParse("2017-02-01", null))); System.out.println(getDate(dateParse("2017-01-17", null))); System.out.println(getDaysOfMonth(dateParse("2017-02-01", null))); System.out.println(getDaysOfYear(dateParse("2017-01-30", null))); /* System.out.println(dateFormat(dateAddMonths(dateParse("2017-02-07", StrUtils.MONTH_PATTERN), -12), StrUtils.MONTH_PATTERN));*/ System.out.println(dateFormat(maxDateOfMonth(dateParse("2016-02", "yyyy-MM")), null)); System.out.println(dateFormat(minDateOfMonth(dateParse("2016-03-31", null)), null)); }
到此这篇关于关于Java日期工具类的编写的文章就介绍到这了,更多相关Java日期工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!