关于Java日期工具类的编写

2023-05-18 17:05:13 日期 工具 编写

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);
	}

    
    public static String formatDate(Date date,String format){
        String result="";
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        if(date!=null){
            result=sdf.format(date);
        }
        return result;
    }
    
    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";
	          
	          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();
	          }
	          
	          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);
	          }
	          
	          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);
	          }
	          
	          public static String dateTimeToDateString(Date dateTime) throws ParseException{
	              String dateTimeString = DateUtils.dateFormat(dateTime, DateUtils.DATE_TIME_PATTERN);  
	              return dateTimeString.substring(0, 10); 
	          }
	             
	             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;
	                 }
	             }
	             
	             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();
	             }
	               
	             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();  
	             }
	             
	             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();  
	             }
	             
	             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();  
	               }	          
	                    
	                  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();  
	                  }
	                    
	                  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();  
	                  }
	                    
	                  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();  
	                  }  
	                    
	                  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);  
	                  }
	                       
	                       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;  
	                       }
	                       
	                       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;  
	                       }
	                       
	                       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); 
	                       }
	                       
	                       public static int dateBetweenIncludeToday(Date startDate, Date endDate) throws ParseException {  
	                           return dateBetween(startDate, endDate) + 1;
	                       }
	                       
	                       public static int getYear(Date date) {  
	                           Calendar cal = Calendar.getInstance();  
	                           cal.setTime(date);
	                           return cal.get(Calendar.YEAR);
	                       }
	                       
	                       public static int getMonth(Date date) {  
	                           Calendar cal = Calendar.getInstance();  
	                           cal.setTime(date);
	                           return cal.get(Calendar.MONTH) + 1;
	                       }
	                       
	                       public static int getDate(Date date) {  
	                           Calendar cal = Calendar.getInstance();  
	                           cal.setTime(date);
	                           return cal.get(Calendar.DATE);
	                       }
	                       
	                       public static int getDaysOfMonth(Date date) {  
	                           Calendar cal = Calendar.getInstance();  
	                           cal.setTime(date);
	                           return cal.getActualMaximum(Calendar.DATE);
	                       }	
	                            
	                            public static int getDaysOfYear(Date date) {  
	                                Calendar cal = Calendar.getInstance();  
	                                cal.setTime(date);
	                                return cal.getActualMaximum(Calendar.DAY_OF_YEAR);
	                            }
	                            
	                            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);
	                            }
	                            
	                            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(maxDateOfMonth(dateParse("2016-02", "yyyy-MM")), null));
	           System.out.println(dateFormat(minDateOfMonth(dateParse("2016-03-31", null)), null));
	}

到此这篇关于关于Java日期工具类的编写的文章就介绍到这了,更多相关Java日期工具类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章