欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

比较时间大小

程序员文章站 2022-06-21 12:30:16
...

 

package com.weboa.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTimeUtil {
	
	/**    
     * 得到几天前的时间    
      *     
      * @param d    
      * @param day    
      * @return    
      */     
     public static Date getDateBefore(Date d, int day) {      
         Calendar now = Calendar.getInstance();      
         now.setTime(d);      
         now.set(Calendar.DATE, now.get(Calendar.DATE) - day);      
         return now.getTime();      
     }     
  /**    
      * 得到几天后的时间    
      *     
      * @param d    
      * @param day    
      * @return    
      */     
     public static String getDateAfter(String startTime, int day) {
    	 String endTime="";
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	Date dateStart;
		try {
			dateStart = sdf.parse(startTime);
			Calendar now = Calendar.getInstance();      
	         now.setTime(dateStart);      
	        now.set(Calendar.DATE, now.get(Calendar.DATE) + day); 
	        endTime=sdf.format(now.getTime());
	               
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return endTime;
        
     }  
     
     
     
     /*
      * java 比较时间大小
      */
      
     public static Integer getDateCompareTo(String startTime, String EndTime) {
    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Calendar c1=Calendar.getInstance();
         Calendar c2=Calendar.getInstance();
         try
         {
         c1.setTime(sdf.parse(startTime));
         c2.setTime(sdf.parse(EndTime));
         }catch(java.text.ParseException e){
        	 System.err.println("格式不正确");
         }
         int result=c1.compareTo(c2);
         return result;
        
     } 
     
     /**    
      * 得到二个日期间的间隔天数    
      */     
  public static String getTwoDay(String sj1, String sj2) {      
      SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
      long day = 0;      
      try {      
       java.util.Date date = myFormatter.parse(sj1);      
       java.util.Date mydate = myFormatter.parse(sj2);      
       day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);      
      } catch (Exception e) {      
       return "";      
      }      
      return day + "";      
  }   
    



}

 

相关标签: Java