DateFormatUtil

来源:互联网 发布:软件解决方案 编辑:程序博客网 时间:2024/05/16 05:20

package com.viewlinecn.commom.util;

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

import org.apache.log4j.Logger;

import com.viewlinecn.tvsysmanager.www.action.game.GameRecordAction;

public class DateFormatUtil {
 private static SimpleDateFormat dateformat = new SimpleDateFormat();
 private static Logger log = Logger.getLogger(GameRecordAction.class);
 public static String formatDateTime(Date date) {
  if (date == null)
   return "";
  dateformat.applyPattern("yyyy-MM-dd HH:mm:ss");
  return dateformat.format(date);
 }
 public static String formatDateTimeByMonth(Date date) {
  if (date == null)
   return "";
  dateformat.applyPattern("yy/MM");
  return dateformat.format(date);
 }
 public static String formatDateTimeByDay(Date date) {
  if (date == null)
   return "";
  dateformat.applyPattern("yy/MM/dd");
  return dateformat.format(date);
 }
 public static String formatDateTimeByHour(Date date) {
  if (date == null)
   return "";
  dateformat.applyPattern("dd/HH:mm");
  return dateformat.format(date);
 }

 public static String formatDate(Date date) {
  if (date == null)
   return "";
  dateformat.applyPattern("yyyy-MM-dd");
  return dateformat.format(date);
 }

 public static String formatTime(Date date) {
  if (date == null)
   return "";
  dateformat.applyPattern("HH:mm:ss");
  return dateformat.format(date);
 }

 /**
  *
  * @param datestring
  *            ig: 2007-11-08
  * @return date
  */
 @SuppressWarnings("deprecation")
 public static Date convertStringToDate(String datestring) {
  Date date = null;
  try {
   
   /*
    * String[] source = datestring.split("-"); int year =
    * Integer.parseInt(source[0]) - 1900; int month =
    * Integer.parseInt(source[1]) - 1; int day =
    * Integer.parseInt(source[2]); date = new Date(year, month, day);
    */
            dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         
            date=dateformat.parse(datestring);
   return date;
  } catch (Exception e) {
   date = null;
   log.error("DateFormatUtil.convertStringToDate() 日期转换发生异常: " + e);
   System.out.println("DateFormatUtil.convertStringToDate() 日期转换发生异常: " + e);
  }
  return date;
 }

 /**
  * 日期加减操作(针对小时数)
  *
  * @param source
  *            源日期
  * @param num
  *            推迟小时数 + 为往后 - 为往前
  * @return
  */
 @SuppressWarnings("static-access")
 public static Date hourRoler(Date source, int num) {
  try {
   Calendar c = Calendar.getInstance();
   c.setTime(source);
   //System.out.println("c.HOUR="+c.HOUR);
   //System.out.println("c.HOUR_OF_DAY="+c.HOUR_OF_DAY);
   c.add(c.HOUR_OF_DAY, num);
   return c.getTime();
  } catch (Exception e) {
   return null;
  }
 }
 
 /**
  * 日期加减操作(针对天数)
  *
  * @param source
  *            源日期
  * @param num
  *            推迟天数 + 为往后 - 为往前
  * @return
  */
 @SuppressWarnings("static-access")
 public static Date dateRoler(Date source, int num) {
  try {
   Calendar c = Calendar.getInstance();
   c.setTime(source);
   c.add(c.DAY_OF_MONTH, num);
   return c.getTime();
  } catch (Exception e) {
   return null;
  }
 }

 /**
  * 日期加减操作(针对月份)
  *
  * @param source
  *            源日期
  * @param num
  *             gc.add(1,-1)表示年份减一. gc.add(2,-1)表示月份减一.
  *            gc.add(3.-1)表示周减一. gc.add(5,-1)表示天减一.
  *
  * @return
  */
 @SuppressWarnings("static-access")
 public static Date dateAddMonth(Date source, int num) {
  try {
   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   GregorianCalendar gc = new GregorianCalendar();
   gc.setTime(source);
   // GregorianCalendar类的add(int field,int amount)方法表示年月日加减.
   // field参数表示年,月.日等. amount参数表示要加减的数量.
            gc.add(2, num);
            return convertStringToDate(df.format(gc.getTime()));
      
  } catch (Exception e) {
   return null;
  }
 }

 /**
  * 计算两日期之间相差的天数 day1 -day2
  *
  * @param day1
  * @param day2
  * @return
  * @throws ParseException
  */
 public static int countDays(String day1, String day2) throws ParseException {

  if (day1 != null && day2 != null && day1.length() > 0
    && day2.length() > 0) {
   // 日期相减算出秒的算法
   Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(day1);
   Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(day2);
   
   // 日期相减得到相差的日期
   long day = (date1.getTime() - date2.getTime())
     / (24 * 60 * 60 * 1000);
   return (int) day;
  } else {
   return 0;
  }

 }

 public static Date string2Date(String dateTimeStr) {
  try {
   if (dateTimeStr == null)
    return null;
   else if (dateTimeStr.trim().length() == 10) {
    dateTimeStr = dateTimeStr.trim() + " 00:00:00";
   }
   dateformat.applyPattern("yyyy-MM-dd HH:mm:ss");
   return dateformat.parse(dateTimeStr.trim());
  } catch (Exception e) {
   return null;
  }

 }

 public static String getDatePart(String dateTimeStr) {
  if (dateTimeStr == null)
   return "";
  else if (dateTimeStr.length() <= 10)
   return dateTimeStr;
  else
   return dateTimeStr.substring(0, 10);
 }

 /**
  * 计算两个日期相差的月份数
  *
  * @param date1
  * @param date2
  * @return
  */
 public static int getMonths(Date date1, Date date2) {
  int iMonth = 0;
  int flag = 0;
  try {
   Calendar objCalendarDate1 = Calendar.getInstance();
   objCalendarDate1.setTime(date1);

   Calendar objCalendarDate2 = Calendar.getInstance();
   objCalendarDate2.setTime(date2);

   if (objCalendarDate2.equals(objCalendarDate1))
    return 0;
   if (objCalendarDate1.after(objCalendarDate2)) {
    Calendar temp = objCalendarDate1;
    objCalendarDate1 = objCalendarDate2;
    objCalendarDate2 = temp;
   }
   if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1
     .get(Calendar.DAY_OF_MONTH))
    flag = 1;

   if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1
     .get(Calendar.YEAR))
    iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1
      .get(Calendar.YEAR))
      * 12 + objCalendarDate2.get(Calendar.MONTH) - flag)
      - objCalendarDate1.get(Calendar.MONTH);
   else
    iMonth = objCalendarDate2.get(Calendar.MONTH)
      - objCalendarDate1.get(Calendar.MONTH) - flag;

  } catch (Exception e) {
   e.printStackTrace();
  }
  return iMonth;
 }
 
 /** 
     * 计算两个日期间相隔的周数 
     *  
     * @param startDate 
     *            开始日期 
     * @param endDate 
     *            结束日期 
     * @return 
     */ 
    public static int computeWeek(Date startDate, Date endDate) {  
 
        int weeks = 0;  
 
        Calendar beginCalendar = Calendar.getInstance();  
        beginCalendar.setTime(startDate);  
 
        Calendar endCalendar = Calendar.getInstance();  
        endCalendar.setTime(endDate);  
 
        while (beginCalendar.before(endCalendar)) {  
 
            // 如果开始日期和结束日期在同年、同月且当前月的同一周时结束循环  
            if (beginCalendar.get(Calendar.YEAR) == endCalendar  
                    .get(Calendar.YEAR)  
                    && beginCalendar.get(Calendar.MONTH) == endCalendar  
                            .get(Calendar.MONTH)  
                    && beginCalendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) == endCalendar  
                            .get(Calendar.DAY_OF_WEEK_IN_MONTH)) {  
                break;  
 
            } else {  
 
                beginCalendar.add(Calendar.DAY_OF_YEAR, 7);  
                weeks += 1;  
            }  
        }  
 
        return weeks;  
    } 
   

 /**
  * 计算两日期之间相差的天数 day1-day2
  *
  * @param date1
  * @param date2
  * @return
  */
 public static int countDays(Date date1, Date date2) {
  if (date1 == null || date2 == null)
   return 0;
  long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000);
  return (int) day;
 }

 /**
  * 计算两日期之间相差的小时数 day1-day2
  * @param date1
  * @param date2
  * @return
  */
 public static int countHours(Date date1, Date date2) {
  if (date1 == null || date2 == null)
   return 0;
  System.out.println("date1.getTime()="+date1.getTime()+",  date2.getTime()=="+date2.getTime());
  long hours = (date1.getTime() - date2.getTime()) / (60 * 60 * 1000);
  System.out.println("hours=="+hours);
  return (int) hours;
 }
   
 public static void  main(String [] args){
  
  
 }
}