`
yeminping
  • 浏览: 176594 次
  • 性别: Icon_minigender_1
  • 来自: 福州
社区版块
存档分类
最新评论

JAVA中不错的处理日期工具单元

    博客分类:
  • JAVA
阅读更多

 /**Revision Information:
*@version 1.0 2006-7-31 release(fanrui)
*/
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateUtilTools {

     /**
          * 方法名: 功能描述: 两个参数格式必须为20050827,而且不能为空。 参数说明: 第一个参数小于第二个参数返回true 返回值: //
          * 函数返回值的说明 其他: // 其它说明
          */
     public static boolean lessThan(String preDate, String date) {
if (preDate == null && date == null) {
      return false;
} else if (preDate == null) {
      return true;
} else if (date == null) {
      return false;
}
preDate = preDate.trim();
date = date.trim();
if (preDate.length() == 8 && date.length() == 8) {
      Integer date1 = new Integer(preDate);
      Integer date2 = new Integer(date);
      if (date1.compareTo(date2) < 0) {
   return true;
      }
}
return false;
     }

     /**
          * 方法名: 功能描述: 两个参数格式必须为20050827,而且不能为空。 参数说明: 第一个参数大于第二个参数返回true 返回值: //
          * 函数返回值的说明 其他: // 其它说明
          */
     public static boolean greaterThan(String preDate, String date) {
if (preDate == null && date == null) {
      return false;
} else if (preDate == null) {
      return false;
} else if (date == null) {
      return true;
}
preDate = preDate.trim();
date = date.trim();
if (preDate.length() == 8 && date.length() == 8) {
      Integer date1 = new Integer(preDate);
      Integer date2 = new Integer(date);
      if (date1.compareTo(date2) > 0) {
   return true;
      }
}
return false;
     }

     /**
          * 方法名: 功能描述: 两个参数格式必须为20050827,而且不能为空。 参数说明: 返回值: // 函数返回值的说明 其他: //
          * 其它说明
          */
     public static boolean equal(String preDate, String date) {
if (preDate == null && date == null) {
      return false;
} else if (preDate == null) {
      return false;
} else if (date == null) {
      return true;
}
preDate = preDate.trim();
date = date.trim();
if (preDate.length() == 8 && date.length() == 8) {
      Integer date1 = new Integer(preDate);
      Integer date2 = new Integer(date);
      if (date1.compareTo(date2) == 0) {
   return true;
      }
}
return false;
     }

     /**
          * @param 19位的时间
          *                 yyyy-MM-dd HH:mm:ss
          * @return 15位的时间 yyyyMMdd HHmmss
          */
     public static String _time19To15(String time_19) {
String time_15 = "";
if (time_19 == null || "".equals(time_19) || time_19.length() != 19) {
      time_15 = "";
} else {
      String[] r = time_19.replace('-', '#').replace(':', '#').split("#");
      for (int i = 0; i < r.length; i++) {
   time_15 += r[i];
      }
}
return time_15;
     }

     /**
          * @param 15位的时间
          *                 yyyyMMdd HHmmss
          * @return 19位的时间 yyyy-MM-dd HH:mm:ss
          */
     public static String _time15To19(String time_15) {
String time_19 = "";
if (time_15 == null || "".equals(time_15) || time_15.length() != 15) {
      time_19 = "";
} else {
      String y = time_15.substring(0, 4);
      String m = time_15.substring(4, 6);
      String d = time_15.substring(6, 8);
      String h = time_15.substring(9, 11);
      String mi = time_15.substring(11, 13);
      String s = time_15.substring(13, 15);
      time_19 = y + "-" + m + "-" + d + " " + h + ":" + mi + ":" + s;
}
return time_19;
     }

     /**
          * @param 16位的时间
          *                 yyyy-MM-dd HH:mm
          * @return 13位的时间 yyyyMMdd HHmm
          */
     public static String _time16To13(String time_16) {
String time_13 = "";
if (time_16 == null || "".equals(time_16) || time_16.length() != 16) {
      time_13 = "";
} else {
      String[] r = time_16.replace('-', '#').replace(':', '#').split("#");
      for (int i = 0; i < r.length; i++) {
   time_13 += r[i];
      }
}
return time_13;
     }

     /**
          * @param 13位的时间
          *                 yyyyMMdd HHmm
          * @return 16位的时间 yyyy-MM-dd HH:mm
          */
     public static String _time13To16(String time_13) {
String time_16 = "";
if (time_13 == null || "".equals(time_13) || time_13.length() != 13) {
      time_16 = "";
} else {
      String y = time_13.substring(0, 4);
      String m = time_13.substring(4, 6);
      String d = time_13.substring(6, 8);
      String h = time_13.substring(9, 11);
      String mi = time_13.substring(11, 13);
      time_16 = y + "-" + m + "-" + d + " " + h + ":" + mi;
}
return time_16;
     }

     /**
          * @param 10位的日期
          *                 yyyy-MM-dd
          * @return 8位的日期 yyyyMMdd
          */
     public static String _date10To8(String date_10) {
String date_8 = "";
if (date_10 == null || "".equals(date_10) || date_10.length() != 10) {
      date_8 = "";
} else {
      String[] r = date_10.split("-");
      for (int i = 0; i < r.length; i++) {
   date_8 += r[i];
      }
}
return date_8;
     }

     /**
          * @param 8位的日期
          *                 yyyyMMdd
          * @return 10位的日期 yyyy-MM-dd
          */
     public static String _date8To10(String date_8) {
String date_10 = "";
if (date_8 == null || "".equals(date_8) || date_8.length() != 8) {
      date_10 = "";
} else {
      String y = date_8.substring(0, 4);
      String m = date_8.substring(4, 6);
      String d = date_8.substring(6, 8);
      date_10 = y + "-" + m + "-" + d;
}
return date_10;
     }

     /**
          * @param 7位的日期
          *                 yyyy-MM
          * @return 6位的日期 yyyyMM
          */
     public static String _date7To6(String date_7) {
String date_6 = "";
if (date_7 == null || "".equals(date_7) || date_7.length() != 7) {
      date_6 = "";
} else {
      String[] r = date_7.split("-");
      for (int i = 0; i < r.length; i++) {
   date_6 += r[i];
      }
}
return date_6;
     }

     /**
          * @param 6位的日期
          *                 yyyyMM
          * @return 7位的日期 yyyy-MM
          */
     public static String _date6To7(String date_6) {
String date_7 = "";
if (date_6 == null || "".equals(date_6) || date_6.length() != 6) {
      date_7 = "";
} else {
      String y = date_6.substring(0, 4);
      String m = date_6.substring(4, 6);
      date_7 = y + "-" + m;
}
return date_7;
     }

     /**
          * Calendar 转 String
          * @param Calendar
          * @return String YYYY-MM-DD HH:mm:ss
          */
     public static String getString(Calendar cal) {
String month = "";
String day = "";
String hour = "";
String minute = "";
String second = "";
if ((cal.get(Calendar.MONTH) + 1) < 10)
      month = "0" + (cal.get(Calendar.MONTH) + 1);
else
      month = "" + (cal.get(Calendar.MONTH) + 1);

if (cal.get(Calendar.DAY_OF_MONTH) < 10)
      day = "0" + cal.get(Calendar.DAY_OF_MONTH);
else
      day = "" + cal.get(Calendar.DAY_OF_MONTH);

if (cal.get(Calendar.HOUR_OF_DAY) < 10)
      hour = "0" + cal.get(Calendar.HOUR_OF_DAY);
else
      hour = "" + cal.get(Calendar.HOUR_OF_DAY);

if (cal.get(Calendar.MINUTE) < 10)
      minute = "0" + cal.get(Calendar.MINUTE);
else
      minute = "" + cal.get(Calendar.MINUTE);

if (cal.get(Calendar.MINUTE) < 10)
      minute = "0" + cal.get(Calendar.MINUTE);
else
      minute = "" + cal.get(Calendar.MINUTE);

if (cal.get(Calendar.SECOND) < 10)
      second = "0" + cal.get(Calendar.SECOND);
else
      second = "" + cal.get(Calendar.SECOND);

return cal.get(Calendar.YEAR) + "-" + month + "-" + day + " " + hour
   + ":" + minute + ":" + second;
     }

     /**
          * @param Calendar
          * @return String YYYY-MM-DD
          */
     public static String getShortString(Calendar cal) {
String month = "";
String day = "";
if ((cal.get(Calendar.MONTH) + 1) < 10)
      month = "0" + (cal.get(Calendar.MONTH) + 1);
else
      month = "" + (cal.get(Calendar.MONTH) + 1);

if (cal.get(Calendar.DAY_OF_MONTH) < 10)
      day = "0" + cal.get(Calendar.DAY_OF_MONTH);
else
      day = "" + cal.get(Calendar.DAY_OF_MONTH);
return cal.get(Calendar.YEAR) + "-" + month + "-" + day;// +"
// "+hour+":"+minute+":"+second;
     }

     /**
          * @param String
          *                 YYYY-MM-DD HH:mm:ss
          * @return Calendar YYYY-MM-DD HH:mm:ss
          */
     public static Calendar toCalender(String time) {

Calendar calendar = Calendar.getInstance();
int year = Integer.parseInt(time.substring(0, 4));
int month = Integer.parseInt(time.substring(5, 7));
int day = Integer.parseInt(time.substring(8, 10));
int hour = Integer.parseInt(time.substring(11, 13));
int munite = Integer.parseInt(time.substring(14, 16));
int second = Integer.parseInt(time.substring(17, 19));
calendar.set(year, month - 1, day, hour, munite, second);
return calendar;
     }

     /**
          * @param String
          *                 YYYY-MM-DD
          * @return Calendar YYYY-MM-DD
          */
     public static Calendar toDateCalender(String time) {
Calendar calendar = Calendar.getInstance();
int year = Integer.parseInt(time.substring(0, 4));
int month = Integer.parseInt(time.substring(5, 7));
int day = Integer.parseInt(time.substring(8, 10));
int hour = Integer.parseInt("00");
int munite = Integer.parseInt("00");
int second = Integer.parseInt("00");
calendar.set(year, month - 1, day, hour, munite, second);
return calendar;
     }

     /**
          * @param String
          * @return Date
          */
     public static java.util.Date stringToDate(String dateStr) {
return java.sql.Date.valueOf(dateStr);
     }

     /**
          * @return 系统时间String
          */
     public static String getSystemTime_String() {
return DateUtilTools.getString(Calendar.getInstance());
     }

     /**
          * @return 系统时间 Date
          */
     public static Date getSystemTimeDate() {
String nowdate = DateUtilTools.getShortString(Calendar.getInstance());
return DateUtilTools.stringToDate(nowdate);
     }

     /**
          * @return 系统时间 String
          */
     public static String getNowTime_String() {
java.util.Date now = new java.util.Date();
return DateUtilTools.getLongTimeStr(now);
     }

     /**
          * 将字符串日期转换为Date对象
          * @param str
          * @return
          * @throws ParseException
          */
     public static Date getDateFromstr(String str) {
Date theDate = null;
if(str.length()<=10){
      str+=" 00:00:00";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
      theDate = sdf.parse(str);
}catch(Exception ex){ex.printStackTrace();}
return theDate;
     }

     /**
          * 将Date时间转换为长日期字符串('yyyy-MM-dd HH:mm:ss'格式)
          * @param t
          * @return
          */
     public static String getLongTimeStr(Date t) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(t);
     }

     /**
          * 将Date时间转换为短日期字符串('yyyy-MM-dd'格式)
          * @param t
          * @return
          */
     public static String getShortTimeStr(Date t) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(t);
     }

/**
   * 将长日期字符串('yyyy-MM-dd HH:mm:ss'格式)转换为短日期字符串('yyyy-MM-dd'格式)
   * @param calendar
   * @return
   */
public static String getShortDateStr(String str) {
int pos = str.indexOf(' ');
if (pos > 0) {
      return str.substring(0, pos);
}
return str;
     }

/**
   * 将长日期字符串('yyyy-MM-dd HH:mm:ss'格式)转换为短时间字符串('HH:mm'格式)
   * @param calendar
   * @return
   */
public static String getShortTimeStr(String str) {
int pos = str.indexOf(' ');
if (pos > 0) {
      str = str.substring(pos + 1);
}
pos = str.lastIndexOf(':');
if (pos > 0) {
      return str.substring(0, pos);
}
return str;
     }

     /**
          * 返回当前的年月 yyyy-mm
          * @return String
          */
     public static String getSysMonth7() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String str = formatter.format(new Date());
if (str == null || "".equals(str)) {
      str = "";
} else {
      str = str.substring(0, 7);
}
return str;
     }
   
     /**
      * 返回当前的年月 yyyymm
      * @return String
      */
public static String getSysMonth6() {
   return getSysMonth7().replaceFirst("-","");
}

     /**
          * 返回当前的整点时间 如:2006-08-07 17:00:00
          * @return
          */
public static String getCurrentDateAndHour() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), 0, 0);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(new Date(cal.getTimeInMillis()));
     }

     /**
          * 返回当前的时间的小时数
          * @return
          */
     public static String getCurrentHour() {
Calendar cal=Calendar.getInstance();
return String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
     }

     /**
          * 返回输入的整点时间 如:2006-08-07 17:00:00
          * @param cal
          * @return
          */
     public static String getCurrentDateAndHour(Calendar cal) {

cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), 0, 0);

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

return formatter.format(new Date(cal.getTimeInMillis()));
     }

     /**
          * 返回输入时间的小时数
          * @param cal
          * @return
          */
     public static String getCurrentHour(Calendar cal) {
return String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
     }

     /**
          * 返回年

          * @return int
          */
     public static int getYear() {
return Calendar.getInstance().get(1);
     }

     /**
          * 返回月
          * @return int
          */
     public static int getMonth() {
return Calendar.getInstance().get(Calendar.MONTH) + 1;
     }

     /**
          * 返回日
          * @return int
          */
     public static int getDay() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
     }

     /**
          * 判断是否是润年

          * @return boolean
          */
     public static boolean isLunYear(int year) {
return (year % 4 == 0 && year % 100 == 0) || year % 400 == 0;
     }

     /**
          * 当前时间,日加两天
          * @return String
          */
     public static String getSdate() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
   .get(Calendar.DATE) + 2);
return DateUtilTools.getShortString(cal);
     }

     /**
          *当前时间,月加一个月
          * @return String
          */
     public static String getEdate() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal
   .get(Calendar.DATE) + 2);
return DateUtilTools.getShortString(cal);
     }

     /**
          * 计算指定年和月的总天数, 要输入年份的原因是要判断二月29天还是28天
          * @param int
          *                 Month ,int Year
          * @return int
          */
     public static int getCountMonth(int Month, int Year) {
int Dates = 0;
if (Month < 0 || Month > 12) {
      System.out.println("Month Error");
}
if (Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8
   || Month == 10 || Month == 12) {
      Dates = 31;
}
if (Month == 2 && DateUtilTools.isLunYear(Year)) {
      Dates = 29;
}
if (Month == 2 && !DateUtilTools.isLunYear(Year)) {
      Dates = 28;
}
if (Month == 4 || Month == 6 || Month == 9 || Month == 11) {
      Dates = 30;
}
return Dates;
     }

     /**
          * 计算当月总天数
          * @return int
          */
     public static int getCountMonth() {
   Calendar thisMonth = Calendar.getInstance();     //声明一个当前日期
   return thisMonth.getActualMaximum(Calendar.DAY_OF_MONTH);     //取得当月共有多少天
     }

    /**
          * 将Date时间转换为短日期字符串('yyyyMMdd'格式)
          * @param t
          * @return
          */
     public static String getShortDateStr(Date t) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
return formatter.format(t);
     }

     /**
      * 比较两个Calendar 的大小,第一个比第二个小 返回 true ,反之 false
      * Calendar cal,Calendar cal2
      * @param cal
      * @param cal2
      * @return boolean
      */
public static boolean compareCalendar(Calendar cal,Calendar cal2)//日期的比较,前者比后者早
{
   return cal.before(cal2);
}

/**
   * 返回两个Calendar 之间的天数
   * @param Calendar cal
   * @param Calendar cal2
   * @return long
   */
     public static long betweenCalendarDays(Calendar cal,Calendar cal2){
      long days=0;
      Date d1=cal.getTime();
      Date d2=cal2.getTime();
      days=d1.getTime()-d2.getTime();
      days=days/3600/24/1000;
      return days;
     }
}

分享到:
评论

相关推荐

    java时间处理工具类--DateUtils

    * 根据日历的规则,为基准时间添加指定日历字段的单个时间单元 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param up * 指定日历字段的值的滚动方向。true:向上滚动 / false:向...

    廖雪峰 Java 教程.doc

    廖雪峰 Java 教程 Java教程 Java快速入门 Java简介 安装JDK 第一个Java程序 Java代码助手 使用IDE 使用IDE练习插件 Java程序基础 Java程序基本结构 变量和数据类型 整数运算 浮点数运算 布尔运算 ...

    Java基础最全笔记文档

    1. Java环境搭建、Java快速入门、IDEA开发工具 2. Java基础语法、类型转换、运算符、Scanner 3. 分支结构、循环结构、随机数 4. 数组详解、Debug工具使用 5. 方法详解 6. 编程思维案例 7. 面向对象基础 8. 常用API 9...

    一个java正则表达式工具类源代码.zip(内含Regexp.java文件)

    在这是junit测试单元类我就不提交了,在main()方法中有几个小测试,有兴趣自己玩吧. 这个工具类目前主要有25种正规表达式(有些不常用,但那时才仔细深入的研究了一下正规,写上瘾了,就当时能想到的都写了): 1....

    Flyer-maker:Java项目的脚手架工具

    集成环境Java 8 SpringBoot2.0.5 / SpringFramework4.3.18 mapper,entity,dao,service,controller以及对应的单元测试第三方工具(guava,jodd,vjkit,apache commons等),满足缓存(内存),串行,日期,json...

    feilong开发工具库.rar

    愿景: Reduce development,Release ideas (减少开发,释放思想), 希望可以减少书写重复且繁杂的代码,让你从大量重复的底层代码中脱身,提高工作效率...有常用专属工具类 (如处理日期的 DateUtil,处理集合的Collectio

    JAVA项目开发全程实录(含电子书和所有源代码)

    《Java项目开发全程实录》这一本书从开发背景、需求分析、系统功能分析、数据库分析、数据库建模、网站开发和网站发布或者程序打包与运行,每一过程都进行了详细的介绍。 目 录 第1章 进销存管理系统(Swing+SQL ...

    DataUtil--数据工具类--数据类型判断和比较

    DataUtil--数据工具类--数据类型判断和比较,包括判断字符串是否为空,判断字符串不为空,判断是否为数字,判断是否为整型数字,判断是否为日期字符串(格式如:2014-04-01),判断是否为时间字符串(格式如:2014-...

    feilong开发工具库-其他

    1、有常用的工具类 (如处理日期的DateUtil,处理集合的CollectionsUtil等) 2、有常用的JAVA常量类 (如日期格式DatePattern,时间间隔TimeInterval等) 3、不必要的Exception 转成了RuntimeException,减少不必要的...

    java-servlet-api.doc

    如果有助于你处理应用的数据需求,你也许需要绑定对象到Session中,你可以通过一个唯一的名字绑定任何的对象到Session中,这时,你需要使用HttpSession对象。任何绑定到Session上的对象都可以被处理同一会话的...

    feilong开发工具库 v3.0.8

    1、有常用的工具类 (如处理日期的DateUtil,处理集合的CollectionsUtil等) 2、有常用的JAVA常量类 (如日期格式DatePattern,时间间隔TimeInterval等) 3、不必要的Exception 转成了RuntimeException,减少不必要的...

    AndroidBase android 应用开发框架.zip

    如网络下载,多线程与线程池的管理,数据库ORM,图片缓存管理,图片文件下载上传,Http请求工具,SOAP工具类,异步Task,常用工具类(字符串,日期,文件处理,图片处理工具) 开发工具在软件开发生命周期中扮演着...

    feilong-core:减少开发,发布想法

    有常用的工具类 (如 处理日期的 DateUtil,处理 集合 的 CollectionsUtil 等)有常用的JAVA常量类 (如日期格式 DatePattern, 时间间隔 TimeInterval 等)不必要的Exception 转成了RuntimeException,减少不必要的代码...

    payment-employee-fee:计算员工支付费用的项目

    Java提供了一组检查日期和时间的工具,因此请使用java.time包中的组件来执行那些验证。 通常,我使用带有模板模式的“策略模式”来执行操作以获取要支付给员工的金额。 最后,为了打印最终结果,我使用了外观模式...

    深入理解Android:卷I--详细书签版

    2.4.8 JNI中的异常处理 32 2.5 本章小结 32 第3章 深入理解init 33 3.1 概述 34 3.2 init分析 34 3.2.1 解析配置文件 38 3.2.2 解析service 42 3.2.3 init控制service 48 3.2.4 属性服务 52 3.3 本章小结 ...

    精通JS脚本之ExtJS框架.part2.rar

    本书共分17章,分别介绍了JavaScript的对象编程、JavaScript浏览器对象模型和事件机制、ExtJS的核心类库和组件、ExtJS的事件处理方式、设计进度条、设计工具栏和菜单栏、设计面板、设计表格、设计表单、设计数据表、...

    精通JS脚本之ExtJS框架.part1.rar

    本书共分17章,分别介绍了JavaScript的对象编程、JavaScript浏览器对象模型和事件机制、ExtJS的核心类库和组件、ExtJS的事件处理方式、设计进度条、设计工具栏和菜单栏、设计面板、设计表格、设计表单、设计数据表、...

    asp.net知识库

    在ASP.NET页面中推荐使用覆写(Override)而不是事件处理(Event Handler) 常用编码工具类,支持base64,md5,des,crc32 也谈谈技术面试 在C#里把ArrayList转换为Array 或 把Array转换为ArrayList C# 2.0 在.NET 2.0中...

    PLSQLDeveloper下载

     PL/SQL(Procedural Language/SQL)是一种过程化语言,属于第三代语言,它与C、C++、Java等语言一样关注于处理细节,可以用来实现比较复杂的业务逻辑。它允许SQL的数据操纵语言和查询语句包含在块结构(block_...

Global site tag (gtag.js) - Google Analytics