首页 > 代码库 > Java Date 日期 时间 相关方法

Java Date 日期 时间 相关方法

DateTools.java

import java.text.SimpleDateFormat;import java.util.Date;/** * 日期操作类 */public class DateTools {    /**yyyyMMddHHmmss     *      * @return     */    public static String getAllDate(){        SimpleDateFormat   lFormat;           //格式可以自己根据需要修改           lFormat   =     new   SimpleDateFormat("yyyyMMddHHmmss");           String   gRtnStr   =   lFormat.format(new Date());         return gRtnStr;    }    /**     * 获得yymmdd类型的日期     * @param date     * @return     */    public static String getDateString(Date date){        String year =(date.getYear()+1900)+"";        String mm = (date.getMonth()+1)+"";        if(Integer.valueOf(mm).intValue()<10){            mm="0"+mm;        }        String day = date.getDate()+"";        if(Integer.valueOf(day).intValue()<10)day="0"+day;        return year+mm+day;    }    /**     * 获得yymmdd类型的日期(日期的前1天)     * @param date     * @return     */    public static String getZDateString(Date date){        date.setDate(date.getDate()-1);        String year =(date.getYear()+1900)+"";        String mm = (date.getMonth()+1)+"";        if(Integer.valueOf(mm).intValue()<10){            mm="0"+mm;        }        String day = date.getDate()+"";        if(day.length()==1)day="0"+day;        return year+mm+day;    }    /**     * 获得yy-mm-dd类型的日期     * @param date     * @return     */    public  static String DateString(Date date){        String year =(date.getYear()+1900)+"";        String mm = (date.getMonth()+1)+"";        if(Integer.valueOf(mm).intValue()<10){            mm="0"+mm;        }        String day = date.getDate()+"";        if(day.length()==1){            day="0"+day;        }        return year+"-"+mm+"-"+day;    }     //得到当前时间    public static String getCurrentDateTime() {        java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();        d.applyPattern("HH:mm:ss");        java.util.Date nowdate = new java.util.Date();        String str_date = d.format(nowdate);        return str_date;    }    /**     * 时间格式化     * @return     */    public static String getTimeString(String time){        String[] ti = time.split(":");        if(ti[1].length()==1){            time = ti[0]+"0"+ti[1];        }else{            time = ti[0]+ti[1];        }        return time;    }    public static String TimeString(){        Date date = new Date();        return getTimeString(date.getHours()+":"+date.getMinutes());    }    public static void main(String args[]){        System.out.println(DateTools.getZDateString(new Date()));            }}

DateTime.java

import java.util.*;import java.text.*;public class DateTime {    public DateTime() {    }    public static final long SECOND = 1000;    public static final long MINUTE = 60 * SECOND;    public static final long HOUR = 60 * MINUTE;    public static final long DAY = 24 * HOUR;    public static final long WEEK = 7 * DAY;    public static final String SHORTFORMAT = "yyyy-MM-dd";    public static final String SHORTFORMATNOSPIT = "yyyyMMdd";    public static final String YEARMONTHFORMAT = "yyyy-MM";    public static final String LONGFORMAT = "yyyy-MM-dd HH:mm:ss";    /**     * 获得yymmdd类型的日期     * @param date     * @return     */    public static String getDateString(Date date){        String year =(date.getYear()+1900)+"";        String mm = (date.getMonth()+1)+"";        if(Integer.valueOf(mm).intValue()<10){            mm="0"+mm;        }        String day = date.getDate()+"";        return year+mm+day;    }    /**     * 获得yy-mm-dd类型的日期     * @param date     * @return     */    public  static String DateString(Date date){        String year =(date.getYear()+1900)+"";        String mm = (date.getMonth()+1)+"";        if(Integer.valueOf(mm).intValue()<10){            mm="0"+mm;        }        String day = date.getDate()+"";        if(day.length()==1){            day="0"+day;        }        return year+"-"+mm+"-"+day;    }     // 得到某一天是星期几    public static int getDateInWeek(String strDate) {        DateFormat df = DateFormat.getDateInstance();        try {            df.parse(strDate);            java.util.Calendar c = df.getCalendar();            int day = c.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;            return day;        } catch (ParseException e) {            return -1;        }    }         //得到当前日期    public static String getCurrentDate() {        java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();        d.applyPattern("yyyy-MM-dd");        java.util.Date nowdate = new java.util.Date();        String str_date = d.format(nowdate);        return str_date;    }         //得到当前日期时间    public static String getCurrentDateTime() {        java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();        d.applyPattern("yyyy-MM-dd HH:mm:ss");        java.util.Date nowdate = new java.util.Date();        String str_date = d.format(nowdate);        return str_date;    }    //根据日期获得日期时间    public static String getDateTime(java.util.Date date) {        java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();        d.applyPattern("yyyy-MM-dd HH:mm:ss");        String str_date = d.format(date);        return str_date;    }    //获得某月的最后一天    public static int getDayNum(int year, int month) {        if (month == 2) {            return year % 400 != 0 && (year % 4 != 0 || year % 100 == 0) ? 28                    : 29;        }        String SmallMonth = ",4,6,9,11,";        return SmallMonth.indexOf(String.valueOf(String                .valueOf((new StringBuffer(",")).append(String.valueOf(month))                        .append(",")))) < 0 ? 31 : 30;    }      //返回两个日期之间隔了多少天      public static int DateDiff(Date date1, Date date2) {        int i = (int) ( (date1.getTime() - date2.getTime()) / 3600 / 24 / 1000);        return i;      }     //从放有日期的字符串中得到,相应的年,月,日 style is "Y"or"y" 返回年 style is "M"or"m" 返回月 style     //is "D"or"d" 返回日 日期字符串要求 "YYYY-MM-DD"    public static int getYearMonthDate(String strDate, String style) {        int year;        int month;        int day;        int firstDash;        int secondDash;        if (strDate == null) {            return 0;        }        firstDash = strDate.indexOf(‘-‘);        secondDash = strDate.indexOf(‘-‘, firstDash + 1);        if ((firstDash > 0) & (secondDash > 0)                & (secondDash < strDate.length() - 1)) {            year = Integer.parseInt(strDate.substring(0, firstDash));            month = Integer.parseInt(strDate.substring(firstDash + 1,                    secondDash));            day = Integer.parseInt(strDate.substring(secondDash + 1));        } else {            return 0;        }        if (style.equalsIgnoreCase("Y")) {            return year;        } else if (style.equalsIgnoreCase("M")) {            return month;        } else if (style.equalsIgnoreCase("D")) {            return day;        } else {            return 0;        }    }     // 某一天,过几天后是几号      public static java.sql.Date DateAdd(java.sql.Date date, int addday) {        java.sql.Date datenew = null;        int year = DateTime.getYearMonthDate(date.toString(), "Y");        int month = DateTime.getYearMonthDate(date.toString(), "M");        int day = DateTime.getYearMonthDate(date.toString(), "D");        day = day + addday;        String dayStr = Integer.toString(year) + "-" + Integer.toString(month) +            "-" + Integer.toString(day);        datenew = datenew.valueOf(dayStr);        //datenew.setTime(datenew.getTime()+day*3600*24*1000);        //有问题。 改        return datenew;      }    //某一天的前几天是几号    public static java.sql.Date DateBefore(java.sql.Date date, int addday) {        java.sql.Date datenew = null;        int year = DateTime.getYearMonthDate(date.toString(), "Y");        int month = DateTime.getYearMonthDate(date.toString(), "M");        int day = DateTime.getYearMonthDate(date.toString(), "D");        day = day - addday;        String dayStr = Integer.toString(year) + "-" + Integer.toString(month)                + "-" + Integer.toString(day);        datenew = datenew.valueOf(dayStr);        // datenew.setTime(datenew.getTime()+day*3600*24*1000);        // 有问题。 改        return datenew;    }    //某一天是否是年的头一天    public static boolean isYearFirstDay(java.sql.Date date) {        boolean i = false;        if ((DateTime.getYearMonthDate(date.toString(), "M") == 1)                && (DateTime.getYearMonthDate(date.toString(), "D") == 1)) {            i = true;        }        return i;    }    // 某一天是否是半年的头一天    public static boolean isHalfYearFirstDay(java.sql.Date date) {        boolean i = false;        if (((DateTime.getYearMonthDate(date.toString(), "M") == 1) && (DateTime                .getYearMonthDate(date.toString(), "D") == 1))                || ((DateTime.getYearMonthDate(date.toString(), "M") == 7) && (DateTime                        .getYearMonthDate(date.toString(), "D") == 1))) {            i = true;        }        return i;    }    public static String getHalfYearFirstDay(java.sql.Date date) {        String month = "01";        if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {            month = "07";        }        String day = Integer.toString(DateTime.getYearMonthDate(date                .toString(), "Y"))                + "-" + month + "-01";        return day;    }    // 某一天是否是半年的最后一天    public static boolean isHalfYearLastDay(java.sql.Date date) {        boolean i = false;        if (((DateTime.getYearMonthDate(date.toString(), "M") == 12) && (DateTime                .getYearMonthDate(date.toString(), "D") == 31))                || ((DateTime.getYearMonthDate(date.toString(), "M") == 6) && (DateTime                        .getYearMonthDate(date.toString(), "D") == 30))) {            i = true;        }        return i;    }    public static String getHalfYearLastDay(java.sql.Date date) {        String month = "-06-30";        if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {            month = "-12-31";        }        String day = Integer.toString(getYearMonthDate(date.toString(), "Y"))                + "-" + month;        return day;    }    // 某一天是否是年的最后一天    public static boolean isYearLastDay(java.sql.Date date) {        boolean i = false;        if ((DateTime.getYearMonthDate(date.toString(), "M") == 12)                && (DateTime.getYearMonthDate(date.toString(), "D") == 31)) {            i = true;        }        return i;    }    //某一天是否是季的头一天        public static boolean isQuarterFirstDay(java.sql.Date date) {        boolean i = false;        if (((DateTime.getYearMonthDate(date.toString(), "M") == 1)                || (DateTime.getYearMonthDate(date.toString(), "M") == 4)                || (DateTime.getYearMonthDate(date.toString(), "M") == 7) || (DateTime                .getYearMonthDate(date.toString(), "M") == 10))                && (DateTime.getYearMonthDate(date.toString(), "D") == 1)) {            i = true;        }        return i;    }    public static String getQuarterFirstDay(java.sql.Date date) {        String month = "01";        if (DateTime.getYearMonthDate(date.toString(), "M") >= 10) {            month = "10";        } else if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {            month = "07";        } else if (DateTime.getYearMonthDate(date.toString(), "M") >= 4) {            month = "04";        } else if (DateTime.getYearMonthDate(date.toString(), "M") >= 1) {            month = "01";        }        String day = Integer.toString(DateTime.getYearMonthDate(date                .toString(), "Y"))                + "-" + month + "-01";        return day;    }    //某一天是否是季的最后一天    public static boolean isQuarterLastDay(java.sql.Date date) {        boolean i = false;        if ((DateTime.getYearMonthDate(date.toString(), "M") == 3)                && (DateTime.getYearMonthDate(date.toString(), "D") == 31)) {            i = true;        }        if ((DateTime.getYearMonthDate(date.toString(), "M") == 6)                && (DateTime.getYearMonthDate(date.toString(), "D") == 30)) {            i = true;        }        if ((DateTime.getYearMonthDate(date.toString(), "M") == 9)                && (DateTime.getYearMonthDate(date.toString(), "D") == 30)) {            i = true;        }        if ((DateTime.getYearMonthDate(date.toString(), "M") == 12)                && (DateTime.getYearMonthDate(date.toString(), "D") == 31)) {            i = true;        }        return i;    }    public static String getQuarterLastDay(java.sql.Date date) {        String month = "-01-31";        if (DateTime.getYearMonthDate(date.toString(), "M") >= 10) {            month = "-12-31";        } else if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {            month = "-09-30";        } else if (DateTime.getYearMonthDate(date.toString(), "M") >= 4) {            month = "-06-30";        }        String day = Integer.toString(DateTime.getYearMonthDate(date                .toString(), "Y"))                + "-" + month;        return day;    }     //某一天是否是月的最后一天    public static boolean isMonthLastDay(java.sql.Date date) {        boolean i = false;        java.sql.Date des_date = null;        String month;        String str_date = date.toString();        String year = str_date.substring(0, str_date.indexOf("-"));        int m = new Integer(str_date.substring(str_date.indexOf("-") + 1,                str_date.lastIndexOf("-"))).intValue() + 1;        month = new Integer(m).toString();        if (m < 10) {            month = "0" + month;        }        java.sql.Date mid_date = null;        mid_date = mid_date.valueOf(year + "-" + month + "-01");        des_date = DateTime.DateAdd(mid_date, -1);        if (DateTime.DateDiff(des_date, date) == 0) {            i = true;        }        return i;    }    //某一天是否是月的第一天    public static boolean isMonthFisrtDay(java.sql.Date date) {        boolean i = false;        if ((DateTime.getYearMonthDate(date.toString(), "D") == 1)) {            i = true;        }        return i;    }    //获得月的第一天    public static String getMonthFisrtDay(java.sql.Date date)    {        String month;        if (DateTime.getYearMonthDate(date.toString(), "M") > 9) {            month = Integer.toString(DateTime.getYearMonthDate(date                    .toString(), "M"));        } else {            month = "0"                    + Integer.toString(DateTime.getYearMonthDate(date                            .toString(), "M"));        }        String day = Integer.toString(DateTime.getYearMonthDate(date                .toString(), "Y"))                + "-" + month + "-01";        return day;    }    public static java.sql.Timestamp getTimestamp() {        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(                    "yyyy-MM-dd HH:mm:ss");            java.util.Calendar calendar = java.util.Calendar.getInstance();            String mystrdate = myFormat.format(calendar.getTime());            return java.sql.Timestamp.valueOf(mystrdate);        } catch (Exception e) {            return null;        }    }    public static java.sql.Timestamp getTimestamp(String datestr) {        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(                    "yyyy-MM-dd HH:mm:ss");            String mystrdate = myFormat.format(myFormat.parse(datestr));            return java.sql.Timestamp.valueOf(mystrdate);        } catch (Exception e) {            return null;        }    }     //格式化日期(Y-年,M-月,D-日 HH:mm:ss 小时:分钟:秒)    public static String getDate(java.util.Date date, String format) {        String result = null;        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(format);            result = myFormat.format(date);        } catch (Exception e) {            return null;        }        return result;    }    public static String getDate(java.util.Date date) {        return getDate(date, LONGFORMAT);    }    //转换成时间戳    public static java.sql.Timestamp getDate(String datestr) {        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(                    "yyyy-MM-dd");            Date date = myFormat.parse(datestr);            myFormat.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss");            String mystrdate = myFormat.format(date);            return java.sql.Timestamp.valueOf(mystrdate);        } catch (Exception e) {            return null;        }    }    //将日期格式化成yyyy-MM-dd形式    public static java.util.Date format(String datestr) {        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(                    "yyyy-MM-dd");            Date date = myFormat.parse(datestr);            return date;        } catch (Exception e) {            return new Date(datestr);        }    }    //格式化日期(Y-年,M-月,D-日 HH:mm:ss 小时:分钟:秒)    public static java.util.Date format(String datestr, String format) {        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(format);            Date date = myFormat.parse(datestr);            return date;        } catch (Exception e) {            return null;        }    }    //获得数据库格式的日期    public static java.sql.Date getSqlDate(java.util.Date date) {        java.sql.Date result = null;        try {            java.text.SimpleDateFormat myFormat = new SimpleDateFormat(                    "yyyy-MM-dd");            String mystrdate = myFormat.format(date);            result = java.sql.Date.valueOf(mystrdate);        } catch (Exception e) {            return null;        }        return result;    }        public static java.util.Date addMonth(java.util.Date date, int month) {        String strdate = getDate(date, SHORTFORMAT);        int curmonth = Integer.parseInt(strdate.substring(5, 7));        int year = Integer.parseInt(strdate.substring(0, 4));        int addyear = month / 12;        year = year + addyear;        curmonth = curmonth + (month % 12);        if (curmonth > 12) {            curmonth = 1;            year = year + 1;        }        String strmonth = String.valueOf(curmonth);        if (strmonth.length() == 1) {            strmonth = "0" + strmonth;        }        strdate = String.valueOf(year) + "-" + strmonth + "-"                + strdate.substring(8, 10);        return format(strdate, SHORTFORMAT);    }        /**     * 传递日期,  获得上个月的最后1天     * @param dt     * @return     */    public static String getUpMDate(Date dt){        dt.setDate(1);        dt.setDate(dt.getDate()-1);        return dt.toLocaleString();    }     /**       *得到当前是那一天。       *       */      public static String getDate() {           java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();            d.applyPattern("yyyy-MM-dd");        java.util.Date nowdate = new java.util.Date();        String str_date = d.format(nowdate);        return str_date;      }        /**     * 将10位日期格式化为8位     * @param dt     * @return     */    public static String getShortDate(String dt){        if(dt != null){            java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");            try {                Date date = myFormat.parse(dt);                return getDate(date,SHORTFORMATNOSPIT);            } catch (ParseException e) {                return dt;            }        }else            return dt;    }        /**     * 将8位日期格式化为10位     * @param dt     * @return     */    public static String getLongDate(String dt){        if(dt != null){            java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");            try {                Date date = myFormat.parse(dt);                return getDate(date,SHORTFORMAT);            } catch (ParseException e) {                return dt;            }        }else            return dt;    }        /**     * 判断是否是当月     * @param month     * @return     */    public static boolean isSameYearMonth(String date){        try{            String currdate = getCurrentDate();            currdate = getShortDate(currdate).substring(0,6);            String lastdate = getShortDate(date).substring(0,6);            if(lastdate.equals(currdate)){                return true;            }else{                return false;            }        }catch(NumberFormatException e){            return false;        }    }               public static void main(String[] args){          Date d = new Date("20070829");          Date f = new Date("20070912");                    System.out.println(d.getDate()-f.getDate());      }}

 

   这几天一直在处理Java的日期问题,通常需要按要求生成日期的话,通常会用到util包中的Calendar类,再用Calendar的getTime()方法生成对应的Date,最后用SimpleDateFormat输出。

 

1. 获取当期日期、年份、月份

import java.util.Calendar;


public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current Year is : " + now.get(Calendar.YEAR));
    // month start from 0 to 11
    System.out.println("Current Month is : " + (now.get(Calendar.MONTH) + 1));
    System.out.println("Current Date is : " + now.get(Calendar.DATE));
  }
}

 

2. 获取前一天、前一个月的日期

Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
        calendar.add(Calendar.DATE, -1);    //
得到前一天

String  yestedayDate

= new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());


        calendar.add(Calendar.MONTH, -1);    //得到前一个月
        int year = calendar.get(Calendar.YEAR);


       int month = calendar.get(Calendar.MONTH)+1; //
输出前一月的时候要记得加1

 

3. 字符串转为日期格式

String date = "2010-02-01 23:59:59";

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

try {

Date d = sf.parse(date);

System.out.println(sf.format(d));

} catch (ParseException e) {

e.printStackTrace();

}

Java Date 日期 时间 相关方法