时间帮助类

一个时间帮助类,可以获得当前时间,也可以指定天数来获取以前的时间,还可以获取当前的日期

一、能满足一般需求的时间帮助类

public class GetTime {
    /**
     * 获取当前时间
     *
     * @param type
     * @return
     */
    public static String getDateToString(String type, long time) {
        SimpleDateFormat sf = new SimpleDateFormat(type);
        Date d = new Date(time);
        return sf.format(d);
    }

    /**
     * 获取指定哪天的日期
     * 如  day=2   就是后天
     * day=-2  就是前天
     *
     * @param day 正数向后推,负数向前推
     * @return
     */
    public static String getLastDateToString(int day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
    }
    public static String getLastDateTimeToString(int day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
    }

    /**
     * 获取当前星期
     *
     * @param date
     * @return
     */
    public static String getWeekday(String date) {//必须yyyy-MM-dd
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdw = new SimpleDateFormat("E");
        Date d = null;
        try {
            d = sd.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();

        }
        return sdw.format(d);

    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

}

二、比较详细的时间帮助类

public class TimeHelper {
        private static String CurrentTime;

    private static String CurrentDate;

    /**
     * 得到当前的年份 返回格式:yyyy
     * 
     * @return String
     */
    public static String getCurrentYear() {
        Date NowDate = new Date();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        return formatter.format(NowDate);
    }

    /**
     * 得到当前的月份 返回格式:MM
     * 
     * @return String
     */
    public static String getCurrentMonth() {
        Date NowDate = new Date();

        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        return formatter.format(NowDate);
    }

    /**
     * 得到当前的日期 返回格式:dd
     * 
     * @return String
     */
    public static String getCurrentDay() {
        Date NowDate = new Date();

        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        return formatter.format(NowDate);
    }
    /**
     * 得到当前的时间,精确到毫秒,共19位 返回格式:yyyy-MM-dd HH:mm:ss
     * 
     * @return String
     */
    public static String getCurrentTime() {
        Date NowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CurrentTime = formatter.format(NowDate);
        return CurrentTime;
    }

    public static String getCurrentCompactTime() {
        Date NowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        CurrentTime = formatter.format(NowDate);
        return CurrentTime;
    }
    
    @SuppressWarnings("static-access")
    public static String getYesterdayCompactTime() {
        Calendar cal = Calendar.getInstance();
        cal.add(cal.DATE, -1); 
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        CurrentTime = formatter.format(cal.getTime());
        return CurrentTime;
    }
    
    @SuppressWarnings("static-access")
    public static String getYesterdayCompactTimeForFileName() {
        Calendar cal = Calendar.getInstance();
        cal.add(cal.DATE, -1); 
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CurrentTime = formatter.format(cal.getTime());
        return CurrentTime;
    }
    /**
     * 得到当前的日期,共10位 返回格式:yyyy-MM-dd
     * 
     * @return String
     */
    public static String getCurrentDate() {
        Date NowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        CurrentDate = formatter.format(NowDate);
        return CurrentDate;
    }
    /**
     * 得到当前的日期,共10位 返回格式:yyyy-MM-dd
     * 
     * @return String
     */
    public static String getCurrentDate1() {
        Date NowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        CurrentDate = formatter.format(NowDate);
        return CurrentDate;
    }
    /**
     * 得到当月的第一天,共10位 返回格式:yyyy-MM-dd
     * 
     * @return String
     */
    public static String getCurrentFirstDate() {
        Date NowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-01");
        CurrentDate = formatter.format(NowDate);
        return CurrentDate;
    }
    /**
     * 得到当月的最后一天,共10位 返回格式:yyyy-MM-dd
     * 
     * @return String
     * @throws ParseException
     */
    public static String getCurrentLastDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=null;
        try {
            Date date =formatter.parse(getCurrentFirstDate());
            calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH,1);
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            return formatDate(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 常用的格式化日期
     *
     * @param date Date
     * @return String
     */
    public static String formatDate(Date date)
    {
        return formatDateByFormat(date,"yyyy-MM-dd");
    }
    /**
     * 以指定的格式来格式化日期
     *
     * @param date Date
     * @param format String
     * @return String
     */
    public static String formatDateByFormat(Date date,String format)
    {
        String result = "";
        if(date != null)
        {
            try
            {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                result = sdf.format(date);
            }
            catch(Exception ex)
            {
                
                ex.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 得到当前日期加上某一个整数的日期,整数代表天数 输入参数:currentdate : String 格式 yyyy-MM-dd add_day :
     * int 返回格式:yyyy-MM-dd
     */
    public static String addDay(String currentdate, int add_day) {
        GregorianCalendar gc = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        int year, month, day;

        try {
            year = Integer.parseInt(currentdate.substring(0, 4));
            month = Integer.parseInt(currentdate.substring(5, 7)) - 1;
            day = Integer.parseInt(currentdate.substring(8, 10));

            gc = new GregorianCalendar(year, month, day);
            gc.add(GregorianCalendar.DATE, add_day);

            return formatter.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 得到当前日期加上某一个整数的日期,整数代表月数 输入参数:currentdate : String 格式 yyyy-MM-dd add_month :
     * int 返回格式:yyyy-MM-dd
     */
    public static String addMonth(String currentdate, int add_month) {
        GregorianCalendar gc = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        int year, month, day;

        try {
            year = Integer.parseInt(currentdate.substring(0, 4));
            month = Integer.parseInt(currentdate.substring(5, 7)) - 1;
            day = Integer.parseInt(currentdate.substring(8, 10));

            gc = new GregorianCalendar(year, month, day);
            gc.add(GregorianCalendar.MONTH, add_month);

            return formatter.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 得到endTime比beforeTime晚几个月,整数代表月数 输入参数:endTime、beforeTime : String 格式前7位的格式为 yyyy-MM 
     */
    public static int monthDiff(String beforeTime,String endTime){
        if(beforeTime==null||endTime==null){
            return 0;
        }
        int beforeYear,endYear,beforeMonth,endMonth;
        try {
            beforeYear = Integer.parseInt(beforeTime.substring(0, 4));
            endYear = Integer.parseInt(endTime.substring(0, 4));
            beforeMonth = Integer.parseInt(beforeTime.substring(5, 7)) - 1;
            endMonth = Integer.parseInt(endTime.substring(5, 7)) - 1;
            return (endYear-beforeYear)*12+(endMonth-beforeMonth);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 得到当前日期加上某一个整数的分钟 输入参数:currentdatetime : String 格式 yyyy-MM-dd HH:mm:ss
     * add_minute : int 返回格式:yyyy-MM-dd HH:mm:ss
     */
    public static String addMinute(String currentdatetime, int add_minute) {
        GregorianCalendar gc = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int year, month, day, hour, minute, second;

        try {
            year = Integer.parseInt(currentdatetime.substring(0, 4));
            month = Integer.parseInt(currentdatetime.substring(5, 7))-1;
            day = Integer.parseInt(currentdatetime.substring(8, 10));

            hour = Integer.parseInt(currentdatetime.substring(11, 13));
            minute = Integer.parseInt(currentdatetime.substring(14, 16));
            second = Integer.parseInt(currentdatetime.substring(17, 19));

            gc = new GregorianCalendar(year, month, day, hour, minute, second);
            gc.add(GregorianCalendar.MINUTE, add_minute);
            return formatter.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 得到当前日期减去某一个整数的分钟 输入参数:currentdatetime : String 格式 yyyy-MM-dd HH:mm:ss
     * minute : int 返回格式:yyyy-MM-dd HH:mm:ss
     */
    @SuppressWarnings("unused")
    public static String reductionMinute(String currentdatetime, int minute) {
        GregorianCalendar gc = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
             Date date = format.parse(currentdatetime);
             long Time=(date.getTime()/1000)-60*minute;
             date.setTime(Time * 1000);
            return format.format(date.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 得到当前日期加上某一个整数的秒 输入参数:currentdatetime : String 格式 yyyy-MM-dd HH:mm:ss
     * add_second : int 返回格式:yyyy-MM-dd HH:mm:ss
     */
    public static String addSecond(String currentdatetime, int add_second) {
        GregorianCalendar gc = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int year, month, day, hour, minute, second;

        try {
            year = Integer.parseInt(currentdatetime.substring(0, 4));
            month = Integer.parseInt(currentdatetime.substring(5, 7))-1;
            day = Integer.parseInt(currentdatetime.substring(8, 10));

            hour = Integer.parseInt(currentdatetime.substring(11, 13));
            minute = Integer.parseInt(currentdatetime.substring(14, 16));
            second = Integer.parseInt(currentdatetime.substring(17, 19));

            gc = new GregorianCalendar(year, month, day, hour, minute, second);
            gc.add(GregorianCalendar.SECOND, add_second);

            return formatter.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static String addMinute1(String currentdatetime, int add_minute) {
        GregorianCalendar gc = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        int year, month, day, hour, minute, second;

        try {
            year = Integer.parseInt(currentdatetime.substring(0, 4));
            month = Integer.parseInt(currentdatetime.substring(5, 7)) - 1;
            day = Integer.parseInt(currentdatetime.substring(8, 10));

            hour = Integer.parseInt(currentdatetime.substring(8, 10));
            minute = Integer.parseInt(currentdatetime.substring(8, 10));
            second = Integer.parseInt(currentdatetime.substring(8, 10));

            gc = new GregorianCalendar(year, month, day, hour, minute, second);
            gc.add(GregorianCalendar.MINUTE, add_minute);

            return formatter.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static Date parseDate(String sDate) {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = bartDateFormat.parse(sDate);
            return date;
        } catch (Exception ex) {
        }
        return null;
    }
    
    public static Date parseDate2(String sDate) {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy/MM/dd");

        try {
            Date date = bartDateFormat.parse(sDate);
            return date;
        } catch (Exception ex) {
        }
        return null;
    }
    
    /**
     * 解析日期及时间
     * 
     * @param sDateTime
     *            日期及时间字符串
     * @return 日期
     */
    public static Date parseDateTime(String sDateTime) {
        SimpleDateFormat bartDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");

        try {
            Date date = bartDateFormat.parse(sDateTime);
            return date;
        } catch (Exception ex) {
        }
        return null;
    }

    /**
     * 取得一个月的天数 date:yyyy-MM-dd
     * 
     * @throws ParseException
     */
    public static int getTotalDaysOfMonth(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();

        Date date = null;
        try {
            date = sdf.parse(strDate);
            calendar.setTime(date);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 天数
        return day;
    }
    
    
    public static long getDateSubDay(String startDate ,String endDate ) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf   =   new SimpleDateFormat("yyyy-MM-dd");
        long theday = 0;
        try  {
            calendar.setTime(sdf.parse(startDate)); 
            long   timethis   =   calendar.getTimeInMillis(); 
            calendar.setTime(sdf.parse(endDate)); 
            long   timeend   =   calendar.getTimeInMillis(); 
            theday   =   (timeend  -  timethis  )   /   (1000   *   60   *   60   *   24); 
        }catch(Exception e) {
            e.printStackTrace();
        }
        return theday;
    }
    /**
     * 方法描述 :获取两个日期时间差
     * @param sDateTime
     * @param eDateTime
     * @return
     * @throws ParseException
     */
    public static String getPlusTime(String sDateTime,String eDateTime) throws ParseException {
         SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Date ssDateTime= myFormatter.parse(sDateTime);
           Date eeDateTime= myFormatter.parse(eDateTime);
         long  l=(eeDateTime.getTime()-ssDateTime.getTime());
           long day=l/(24*60*60*1000);
           long hour=(l/(60*60*1000)-day*24);
           long min=((l/(60*1000))-day*24*60-hour*60);
           long s=(l/1000-day*24*60*60-hour*60*60-min*60);
           return ""+day+"天"+hour+"小时"+min+"分"+s+"秒";
    }
    /**
     * 方法描述 :获取两个日期时间差
     * @param sDateTime
     * @param eDateTime
     * @return
     * @throws ParseException
     */
    public static int getTime(String sDateTime,String eDateTime) throws ParseException {
         SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
           Date ssDateTime= myFormatter.parse(sDateTime);
           Date eeDateTime= myFormatter.parse(eDateTime);
         long  l=(eeDateTime.getTime()-ssDateTime.getTime());
           long day=l/(24*60*60*1000);
           return (int)day;
    }
    /**
     * 方法描述 : 获取时间差
     * @param sDateTime
     * @param eDateTime
     * @return
     * @throws ParseException
     */
    public static long getPlusTotalTime(String sDateTime,String eDateTime) throws ParseException {
         SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Date ssDateTime= myFormatter.parse(sDateTime);
           Date eeDateTime= myFormatter.parse(eDateTime);
           return  (eeDateTime.getTime()-ssDateTime.getTime());
    }
     /**  
     * 根据一个日期,返回是星期几的字符串  
     *   
     * @param sdate  
     * @return  
     */  
 public static String getWeek(String sdate) {
     // 再转换为时间   
     Date date = TimeHelper.strToDate(sdate);
     Calendar c = Calendar.getInstance();
     c.setTime(date);   
     // int hour=c.get(Calendar.DAY_OF_WEEK);   
     // hour中存的就是星期几了,其范围 1~7   
     // 1=星期日 7=星期六,其他类推   
     return new SimpleDateFormat("EEEE").format(c.getTime());
 }   

 /**  
     * 将短时间格式字符串转换为时间 yyyy-MM-dd   
     *   
     * @param strDate  
     * @return  
     */  
 public static Date strToDate(String strDate) {
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
     ParsePosition pos = new ParsePosition(0);
     Date strtodate = formatter.parse(strDate, pos);
     return strtodate;   
 }   
 
    public static String convertToString(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return formatter.format(date);
        } catch (Exception e) {
            // e.printStackTrace();
            return null;
        }
    }
     /**  
     * 得到二个日期间的间隔天数  
     */  
 public static String getTwoDay(String sj1, String sj2) {
     SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
     long day = 0;   
     try {   
      Date date = myFormatter.parse(sj1);
      Date mydate = myFormatter.parse(sj2);
      day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);   
     } catch (Exception e) {
      return "";   
     }   
     return day + "";   
 }   
    /**
     * 方法描述 : 将毫秒装换成日期
     * @param sDateTime
     * @param eDateTime
     * @return
     * @throws ParseException
     */
    public static String getTimeByMillis(long now) throws ParseException {
          DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
          Calendar calendar = Calendar.getInstance();
          calendar.setTimeInMillis(now);
          return formatter.format(calendar.getTimeInMillis());
    }
    
    public static void main(String[] args) throws ParseException {
        System.out.println(new TimeHelper().getCurrentYear());
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335

推荐阅读更多精彩内容