测试类
/** * @Description TestDateUtil.java * @author 张军 * @date 2021年10月19日 下午11:18:23 * @version V1.0 */ package test.share; import java.util.Date; import org.junit.Test; import test.all.TestUtil; import zj.date.util.DateUtil; import zj.java.util.JavaUtil; /** * @author 张军 * @date 2021年10月19日 下午11:18:23 * @version V1.0 */ public class TestDateUtil { @Test public void 基本工具类() { System.out.println("日期转字符串"); System.out.println(DateUtil.dateParse(new Date(), "yyyy年MM月dd日HH时mm分ss秒SSS毫秒p(0-6=>周日-周六)w x q季度")); System.out.println("字符串转日期"); System.out.println(DateUtil.parseDate("2019-07-30")); System.out.println(DateUtil.parseDate("2019-07-30 10:11:12")); System.out.println(DateUtil.parseDate("20190730")); System.out.println(DateUtil.parseDate("20190730101112")); System.out.println(DateUtil.parseDate("2019/07/30 10:11:12")); System.out.println(DateUtil.parseDate("2019-07-30 10:11")); System.out.println(DateUtil.parseDate("2019/07/30 10:11")); System.out.println(DateUtil.parseDate("2019/07/30 10")); System.out.println(DateUtil.parseDate("2019-07-30 10")); System.out.println("日期相差天数"); System.out.println("2019-02-25到2019-03-10共" + DateUtil.diffDay(DateUtil.parseDate("2019-02-25"), DateUtil.parseDate("2019-03-10")) + "天"); System.out.println("2019-02-25加10天是" + DateUtil.dateParse(DateUtil.addDay(DateUtil.parseDate("2019-02-25"), 10), "yyyy-MM-dd")); System.out.println("对日期或时间相加减就不多做测试了"); System.out.println(DateUtil.dateParse(new Date(), "yyy-MM-ddw")); System.out.println(DateUtil.getDescWeekday(DateUtil.dateParse(new Date(), "w"))); System.out.println(DateUtil.dateParse(DateUtil.parseDate("20200820080301"), "HH24点m分ss秒")); } @Test public void 时间相差() { String sd = "1234年56月78日 星期三"; sd = "01月03日 星期日 03:20"; String t = "91:23"; // String s = sd + t; String V_sdateNum = JavaUtil.conversionStringToNumber(sd) + "00"; if (V_sdateNum.length() == 10) { V_sdateNum = DateUtil.dateParse(new Date(), "yyyy") + V_sdateNum; } System.out.println(JavaUtil.split(sd.replace("年", "").replace("月", "").replace("日", ""), " ")[0]); System.out.println(t.replace(":", "") + "00"); System.out.println(V_sdateNum); System.out.println(DateUtil.dateParse(DateUtil.parseDate(V_sdateNum))); Date d = new Date(); d.setTime(1625713200000l); System.out.println(DateUtil.dateParse(d)); System.out.println(DateUtil.dateParse(DateUtil.addMonth(DateUtil.parseDate("2020-01-31"), 1))); } @Test public void 日期范围() { TestUtil.printStart("查询日期范围"); Date startDate = DateUtil.parseDate("2021"); String sstartDate = DateUtil.dateParse(startDate, "yyyy-MM-dd"); String sendDate = DateUtil.dateParse(DateUtil.addYear(startDate, 3), "yyyy-MM-dd"); long diffDays = DateUtil.diffDay(DateUtil.parseDate(sstartDate), DateUtil.parseDate(sendDate)); System.out.println(sstartDate + "到" + sendDate + "共" + diffDays + "天,以下是循环每一天"); for (int a = 0; a <= diffDays; a++) { Date d = DateUtil.addDay(DateUtil.parseDate(sstartDate), a); // String tdate = DateUtil.dateParse(d, "yyyy年MM月dd日 ") + DateUtil.getDescWeekday(DateUtil.dateParse(d, "w")); String tdate = DateUtil.dateParse(d, "yyyyMMdd"); // String tdate = DateUtil.dateParse(d, "MM月dd日 ") + DateUtil.getDescWeekday(DateUtil.dateParse(d, "w")); // String tdate = DateUtil.dateParse(d, "yyyy"); System.out.println("'" + tdate + "',"); } TestUtil.printEnd("查询日期范围"); } }
测试结果
日期转字符串 2021年10月19日23时20分22秒894毫秒下午(0-6=>周日-周六)2 星期二 4季度 字符串转日期 Tue Jul 30 00:00:00 CST 2019 Tue Jul 30 10:11:12 CST 2019 Tue Jul 30 00:00:00 CST 2019 Tue Jul 30 10:11:12 CST 2019 Tue Jul 30 10:11:12 CST 2019 Tue Jul 30 10:11:00 CST 2019 Tue Jul 30 10:11:00 CST 2019 Tue Jul 30 10:00:00 CST 2019 Tue Jul 30 10:00:00 CST 2019 日期相差天数 2019-02-25到2019-03-10共13天 2019-02-25加10天是2019-03-07 对日期或时间相加减就不多做测试了 21y-10-192 星期二 08点3分01秒 查询日期范围------>测试开始 2021-01-01到2024-01-01共1095天,以下是循环每一天 '20210101', '20210102', '20210103', '20210104', '20210105', '20210106', '20210107', '20210108', '20210109', '20210110', '20210111', '20210112', '20210113', '20210114', '20210115', '20210116', '20210117', '20210118', '20210119', '20210120', '20210121', '20210122', '20210123', '20210124', '20210125', '20210126', '20210127', '20210128', '20210129', '20210130', '20210131', '20210201', '20210202', '20210203', '20210204', '20210205', '20210206', '20210207', '20210208', '20210209', '20210210', '20210211', '20210212', '20210213', '20210214', '20210215', '20210216', '20210217', '20210218', '20210219', '20210220', '20210221', '20210222', '20210223', '20210224', '20210225', '20210226', '20210227', '20210228', '20210301', '20210302', '20210303', '20210304', '20210305', '20210306', '20210307', '20210308', '20210309', '20210310', '20210311', '20210312', '20210313', '20210314', '20210315', '20210316', '20210317', '20210318', '20210319', '20210320', '20210321', '20210322', '20210323', '20210324', '20210325', '20210326', '20210327', '20210328', '20210329', '20210330', '20210331', '20210401', '20210402', '20210403', '20210404', '20210405', '20210406', '20210407', '20210408', '20210409', '20210410', '20210411', '20210412', '20210413', '20210414', '20210415', '20210416', '20210417', '20210418', '20210419', '20210420', '20210421', '20210422', '20210423', '20210424', '20210425', '20210426', '20210427', '20210428', '20210429', '20210430', '20210501', '20210502', '20210503', '20210504', '20210505', '20210506', '20210507', '20210508', '20210509', '20210510', '20210511', '20210512', '20210513', '20210514', '20210515', '20210516', '20210517', '20210518', '20210519', '20210520', '20210521', '20210522', '20210523', '20210524', '20210525', '20210526', '20210527', '20210528', '20210529', '20210530', '20210531', '20210601', '20210602', '20210603', '20210604', '20210605', '20210606', '20210607', '20210608', '20210609', '20210610', '20210611', '20210612', '20210613', '20210614', '20210615', '20210616', '20210617', '20210618', '20210619', '20210620', '20210621', '20210622', '20210623', '20210624', '20210625', '20210626', '20210627', '20210628', '20210629', '20210630', '20210701', '20210702', '20210703', '20210704', '20210705', '20210706', '20210707', '20210708', '20210709', '20210710', '20210711', '20210712', '20210713', '20210714', '20210715', '20210716', '20210717', '20210718', '20210719', '20210720', '20210721', '20210722', '20210723', '20210724', '20210725', '20210726', '20210727', '20210728', '20210729', '20210730', '20210731', '20210801', '20210802', '20210803', '20210804', '20210805', '20210806', '20210807', '20210808', '20210809', '20210810', '20210811', '20210812', '20210813', '20210814', '20210815', '20210816', '20210817', '20210818', '20210819', '20210820', '20210821', '20210822', '20210823', '20210824', '20210825', '20210826', '20210827', '20210828', '20210829', '20210830', '20210831', '20210901', '20210902', '20210903', '20210904', '20210905', '20210906', '20210907', '20210908', '20210909', '20210910', '20210911', '20210912', '20210913', '20210914', '20210915', '20210916', '20210917', '20210918', '20210919', '20210920', '20210921', '20210922', '20210923', '20210924', '20210925', '20210926', '20210927', '20210928', '20210929', '20210930', '20211001', '20211002', '20211003', '20211004', '20211005', '20211006', '20211007', '20211008', '20211009', '20211010', '20211011', '20211012', '20211013', '20211014', '20211015', '20211016', '20211017', '20211018', '20211019', '20211020', '20211021', '20211022', '20211023', '20211024', '20211025', '20211026', '20211027', '20211028', '20211029', '20211030', '20211031', '20211101', '20211102', '20211103', '20211104', '20211105', '20211106', '20211107', '20211108', '20211109', '20211110', '20211111', '20211112', '20211113', '20211114', '20211115', '20211116', '20211117', '20211118', '20211119', '20211120', '20211121', '20211122', '20211123', '20211124', '20211125', '20211126', '20211127', '20211128', '20211129', '20211130', '20211201', '20211202', '20211203', '20211204', '20211205', '20211206', '20211207', '20211208', '20211209', '20211210', '20211211', '20211212', '20211213', '20211214', '20211215', '20211216', '20211217', '20211218', '20211219', '20211220', '20211221', '20211222', '20211223', '20211224', '20211225', '20211226', '20211227', '20211228', '20211229', '20211230', '20211231', '20220101', '20220102', '20220103', '20220104', '20220105', '20220106', '20220107', '20220108', '20220109', '20220110', '20220111', '20220112', '20220113', '20220114', '20220115', '20220116', '20220117', '20220118', '20220119', '20220120', '20220121', '20220122', '20220123', '20220124', '20220125', '20220126', '20220127', '20220128', '20220129', '20220130', '20220131', '20220201', '20220202', '20220203', '20220204', '20220205', '20220206', '20220207', '20220208', '20220209', '20220210', '20220211', '20220212', '20220213', '20220214', '20220215', '20220216', '20220217', '20220218', '20220219', '20220220', '20220221', '20220222', '20220223', '20220224', '20220225', '20220226', '20220227', '20220228', '20220301', '20220302', '20220303', '20220304', '20220305', '20220306', '20220307', '20220308', '20220309', '20220310', '20220311', '20220312', '20220313', '20220314', '20220315', '20220316', '20220317', '20220318', '20220319', '20220320', '20220321', '20220322', '20220323', '20220324', '20220325', '20220326', '20220327', '20220328', '20220329', '20220330', '20220331', '20220401', '20220402', '20220403', '20220404', '20220405', '20220406', '20220407', '20220408', '20220409', '20220410', '20220411', '20220412', '20220413', '20220414', '20220415', '20220416', '20220417', '20220418', '20220419', '20220420', '20220421', '20220422', '20220423', '20220424', '20220425', '20220426', '20220427', '20220428', '20220429', '20220430', '20220501', '20220502', '20220503', '20220504', '20220505', '20220506', '20220507', '20220508', '20220509', '20220510', '20220511', '20220512', '20220513', '20220514', '20220515', '20220516', '20220517', '20220518', '20220519', '20220520', '20220521', '20220522', '20220523', '20220524', '20220525', '20220526', '20220527', '20220528', '20220529', '20220530', '20220531', '20220601', '20220602', '20220603', '20220604', '20220605', '20220606', '20220607', '20220608', '20220609', '20220610', '20220611', '20220612', '20220613', '20220614', '20220615', '20220616', '20220617', '20220618', '20220619', '20220620', '20220621', '20220622', '20220623', '20220624', '20220625', '20220626', '20220627', '20220628', '20220629', '20220630', '20220701', '20220702', '20220703', '20220704', '20220705', '20220706', '20220707', '20220708', '20220709', '20220710', '20220711', '20220712', '20220713', '20220714', '20220715', '20220716', '20220717', '20220718', '20220719', '20220720', '20220721', '20220722', '20220723', '20220724', '20220725', '20220726', '20220727', '20220728', '20220729', '20220730', '20220731', '20220801', '20220802', '20220803', '20220804', '20220805', '20220806', '20220807', '20220808', '20220809', '20220810', '20220811', '20220812', '20220813', '20220814', '20220815', '20220816', '20220817', '20220818', '20220819', '20220820', '20220821', '20220822', '20220823', '20220824', '20220825', '20220826', '20220827', '20220828', '20220829', '20220830', '20220831', '20220901', '20220902', '20220903', '20220904', '20220905', '20220906', '20220907', '20220908', '20220909', '20220910', '20220911', '20220912', '20220913', '20220914', '20220915', '20220916', '20220917', '20220918', '20220919', '20220920', '20220921', '20220922', '20220923', '20220924', '20220925', '20220926', '20220927', '20220928', '20220929', '20220930', '20221001', '20221002', '20221003', '20221004', '20221005', '20221006', '20221007', '20221008', '20221009', '20221010', '20221011', '20221012', '20221013', '20221014', '20221015', '20221016', '20221017', '20221018', '20221019', '20221020', '20221021', '20221022', '20221023', '20221024', '20221025', '20221026', '20221027', '20221028', '20221029', '20221030', '20221031', '20221101', '20221102', '20221103', '20221104', '20221105', '20221106', '20221107', '20221108', '20221109', '20221110', '20221111', '20221112', '20221113', '20221114', '20221115', '20221116', '20221117', '20221118', '20221119', '20221120', '20221121', '20221122', '20221123', '20221124', '20221125', '20221126', '20221127', '20221128', '20221129', '20221130', '20221201', '20221202', '20221203', '20221204', '20221205', '20221206', '20221207', '20221208', '20221209', '20221210', '20221211', '20221212', '20221213', '20221214', '20221215', '20221216', '20221217', '20221218', '20221219', '20221220', '20221221', '20221222', '20221223', '20221224', '20221225', '20221226', '20221227', '20221228', '20221229', '20221230', '20221231', '20230101', '20230102', '20230103', '20230104', '20230105', '20230106', '20230107', '20230108', '20230109', '20230110', '20230111', '20230112', '20230113', '20230114', '20230115', '20230116', '20230117', '20230118', '20230119', '20230120', '20230121', '20230122', '20230123', '20230124', '20230125', '20230126', '20230127', '20230128', '20230129', '20230130', '20230131', '20230201', '20230202', '20230203', '20230204', '20230205', '20230206', '20230207', '20230208', '20230209', '20230210', '20230211', '20230212', '20230213', '20230214', '20230215', '20230216', '20230217', '20230218', '20230219', '20230220', '20230221', '20230222', '20230223', '20230224', '20230225', '20230226', '20230227', '20230228', '20230301', '20230302', '20230303', '20230304', '20230305', '20230306', '20230307', '20230308', '20230309', '20230310', '20230311', '20230312', '20230313', '20230314', '20230315', '20230316', '20230317', '20230318', '20230319', '20230320', '20230321', '20230322', '20230323', '20230324', '20230325', '20230326', '20230327', '20230328', '20230329', '20230330', '20230331', '20230401', '20230402', '20230403', '20230404', '20230405', '20230406', '20230407', '20230408', '20230409', '20230410', '20230411', '20230412', '20230413', '20230414', '20230415', '20230416', '20230417', '20230418', '20230419', '20230420', '20230421', '20230422', '20230423', '20230424', '20230425', '20230426', '20230427', '20230428', '20230429', '20230430', '20230501', '20230502', '20230503', '20230504', '20230505', '20230506', '20230507', '20230508', '20230509', '20230510', '20230511', '20230512', '20230513', '20230514', '20230515', '20230516', '20230517', '20230518', '20230519', '20230520', '20230521', '20230522', '20230523', '20230524', '20230525', '20230526', '20230527', '20230528', '20230529', '20230530', '20230531', '20230601', '20230602', '20230603', '20230604', '20230605', '20230606', '20230607', '20230608', '20230609', '20230610', '20230611', '20230612', '20230613', '20230614', '20230615', '20230616', '20230617', '20230618', '20230619', '20230620', '20230621', '20230622', '20230623', '20230624', '20230625', '20230626', '20230627', '20230628', '20230629', '20230630', '20230701', '20230702', '20230703', '20230704', '20230705', '20230706', '20230707', '20230708', '20230709', '20230710', '20230711', '20230712', '20230713', '20230714', '20230715', '20230716', '20230717', '20230718', '20230719', '20230720', '20230721', '20230722', '20230723', '20230724', '20230725', '20230726', '20230727', '20230728', '20230729', '20230730', '20230731', '20230801', '20230802', '20230803', '20230804', '20230805', '20230806', '20230807', '20230808', '20230809', '20230810', '20230811', '20230812', '20230813', '20230814', '20230815', '20230816', '20230817', '20230818', '20230819', '20230820', '20230821', '20230822', '20230823', '20230824', '20230825', '20230826', '20230827', '20230828', '20230829', '20230830', '20230831', '20230901', '20230902', '20230903', '20230904', '20230905', '20230906', '20230907', '20230908', '20230909', '20230910', '20230911', '20230912', '20230913', '20230914', '20230915', '20230916', '20230917', '20230918', '20230919', '20230920', '20230921', '20230922', '20230923', '20230924', '20230925', '20230926', '20230927', '20230928', '20230929', '20230930', '20231001', '20231002', '20231003', '20231004', '20231005', '20231006', '20231007', '20231008', '20231009', '20231010', '20231011', '20231012', '20231013', '20231014', '20231015', '20231016', '20231017', '20231018', '20231019', '20231020', '20231021', '20231022', '20231023', '20231024', '20231025', '20231026', '20231027', '20231028', '20231029', '20231030', '20231031', '20231101', '20231102', '20231103', '20231104', '20231105', '20231106', '20231107', '20231108', '20231109', '20231110', '20231111', '20231112', '20231113', '20231114', '20231115', '20231116', '20231117', '20231118', '20231119', '20231120', '20231121', '20231122', '20231123', '20231124', '20231125', '20231126', '20231127', '20231128', '20231129', '20231130', '20231201', '20231202', '20231203', '20231204', '20231205', '20231206', '20231207', '20231208', '20231209', '20231210', '20231211', '20231212', '20231213', '20231214', '20231215', '20231216', '20231217', '20231218', '20231219', '20231220', '20231221', '20231222', '20231223', '20231224', '20231225', '20231226', '20231227', '20231228', '20231229', '20231230', '20231231', '20240101', 查询日期范围------>测试结束 0103 912300 20210103032000 2021年01月03日03时20分00秒000毫秒上午(1-7=>周一-周日)7 星期日 1季度 2021年07月08日11时00分00秒000毫秒上午(1-7=>周一-周日)4 星期四 3季度 2020年02月29日00时00分00秒000毫秒上午(1-7=>周一-周日)6 星期六 1季度
工具类
package zj.date.util; import java.io.File; import java.io.Serializable; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import zj.cache.util.EhCacheUtil; import zj.check.util.CheckUtil; import zj.common.exception.ServiceException; import zj.date.bean.TradeDate; import zj.io.util.FileUtil; import zj.java.util.JavaUtil; import zj.type.TypeUtil; /** * * 日期工具类 * <p> * 一般,在项目中,我们会会经常使用到日期的各种方式的处理,在各个业务逻辑操作中,都需要相关的日期操作, 因此,实现项目中的日期工具类的提出,还是十分重要的,下面,就项目中常用到的日期的相关操作方式, 做了一个小的工具类,几乎包含所有的日期操作了,方便项目使用,也方便以后的复用和查询.下面见代码: * </p> * * @version 1.00 (2014.09.15) * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">上海加盾信息科技有限公司</a> <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} * */ public class DateUtil implements Serializable { private static final long serialVersionUID = 1L; private transient static final Logger log = Logger.getLogger(DateUtil.class); public static final String EHCACHE_HOLIDAY_DATE = "holidayDate"; /** * 获取域名IP * * @return */ public static String ipByDomain(String P_url) { try { if (P_url.startsWith("https://")) { P_url = P_url.substring("https://".length()); } if (P_url.startsWith("http://")) { P_url = P_url.substring("http://".length()); } InetAddress R_ia = InetAddress.getByName(P_url); return R_ia.getHostAddress(); } catch (Exception e) { throw new RuntimeException("[错误] 获取域名IP", e); } } /** * 判断域名是否是指定IP地址 * * @param P_url * 域名 * @param P_ip * IP地址 * @return */ public static boolean ipCheckByDomain(String P_url, String P_ip) { try { String R_ip = ipByDomain(P_url); return R_ip.equals(P_ip); } catch (Exception e) { throw new RuntimeException("[错误] 判断域名是否是指定IP地址", e); } } /** * 获取指定网站的日期时间 * * @param P_url * 域名 * @return 日期 */ public static Date ipDate(String P_url) { return ipDate(P_url, null); } /** * 获取指定网站的日期时间 * * @param P_url * 域名 * @param P_ip * IP地址 * @return 日期 */ public static Date ipDate(String P_url, String P_ip) { try { if (CheckUtil.isNotNull(P_ip) && !ipCheckByDomain(P_url, P_ip)) { // 如果为映射IP,则不行 return null; } if (!P_url.startsWith("https://") && !P_url.startsWith("http://")) { P_url = "http://" + P_url; } // 取得资源对象 URL url = new URL(P_url); // 生成连接对象 URLConnection uc = url.openConnection(); uc.connect();// 发出连接 long ld = uc.getDate();// 读取网站日期时间 Date date = new Date(ld);// 转换为标准时间对象 // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间 // return sdf.format(date); return date; } catch (Exception e) { return null; } } // =====================================================交易日====================================== // DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA); // String value = "'" + formatter.format(new Date()) + "'"; // System.out.println(value); // /** // * 初使化节假日数据 // * // * @param conn // * 数据库连接 // * @return // */ // public static void cacheHoliday(Connection conn) { // Map<String, String> holidayMap = new HashMap<String, String>(); // PreparedStatement psQuery = null; // ResultSet rs = null; // try { // String sql = "select date_format(a.c_date,'%Y%m%d') c_date,a.c_desc from dc_trade_date a where a.is_trade_date=2"; // psQuery = conn.prepareStatement(sql); // rs = psQuery.executeQuery(); // while (rs.next()) { // holidayMap.put(rs.getString(1), rs.getString(2)); // } // EhCacheUtil.put(Constant.EHCACHE_HOLIDAY_DATE, holidayMap); // logger.info("缓存节假日数据成功:" + holidayMap.size()); // } catch (Exception e) { // throw new ServiceException(e); // } finally { // JdbcUtil.closeDB(rs, psQuery); // } // } /** * 取上一个交易日 * * @param td * 参数信息 * @return */ public static final Date preTradeDate() { TradeDate td = new TradeDate(); td.beforeCurrent = true; return tradeDate(td); } /** * 取下一个交易日 * * @param td * 参数信息 * @return */ public static final Date nextTradeDate() { TradeDate td = new TradeDate(); td.beforeCurrent = false; return tradeDate(td); } /** * 取交易日[不包含当前日期] * * @param td * 参数信息 * @return */ public static final Date tradeDate(TradeDate td) { Map<String, String> holidayMap = EhCacheUtil.get(EHCACHE_HOLIDAY_DATE); if (holidayMap == null || holidayMap.size() == 0) { throw new ServiceException("未初使化交易日文件,请执行DateUtil.initTradeDate(file)"); } /** 当前日期 **/ if (td.current == null) { td.current = new Date(); } Date current = td.current; // ========================================== /** 类型[默认0:天,1:周,2:月,3:季度,4:年] **/ int type = td.type; /** 当前日期前后,默认前(和类型做匹配使用) **/ boolean beforeCurrent = td.beforeCurrent; // ========================================== /** 交易日前后,默认前 **/ boolean beforeTradeDate = td.beforeTradeDate; // ========================================== /** 递归次数 **/ int recursionCount = td.recursionCount; // 首先取上一个日期 if (type == 1) { // 加减7天 current = DateUtil.addDay(current, beforeCurrent ? -7 : 7); } else if (type == 2) { // 加减1个月 current = DateUtil.addMonth(current, beforeCurrent ? -1 : 1); } else if (type == 3) { // 加减3个月 current = DateUtil.addMonth(current, beforeCurrent ? -3 : 3); } else if (type == 4) { // 加减1年 current = DateUtil.addYear(current, beforeCurrent ? -1 : 1); } else { // 加减1天 current = DateUtil.addDay(current, beforeCurrent ? -1 : 1); } // 交易日前还是后+(1)T日 int addDay = beforeTradeDate ? -1 : 1; // 加一天 while (holidayMap.containsKey(DateUtil.dateParse(current, "yyyyMMdd"))) { // 是否是节假日 current = DateUtil.addDay(current, addDay); } if (recursionCount <= 1) { return current; } else { td.current = current; td.recursionCount = td.recursionCount - 1; return tradeDate(td); } } /** * 取交易日 * * @param P_date * 交易日 * @param P_nums * T日(正表示T+P_nums或负表示T-P_nums) * @return */ public static final Date tradeDate(Date P_date, int P_nums) { Map<String, String> holidayMap = EhCacheUtil.get(EHCACHE_HOLIDAY_DATE); if (holidayMap == null || holidayMap.size() == 0) { throw new ServiceException("未初使化交易日文件,请执行DateUtil.initTradeDate(file)"); } // 临时变量 Date V_current = P_date; int addDay = 0; if (P_nums > 0) { // 往后推 addDay = 1; } else if (P_nums < 0) { // 往前推 addDay = -1; } else { // 不处理 return P_date; } // 取绝对值 P_nums = Math.abs(P_nums); while (P_nums > 0) { // 加减一天,判断是否是交易日 V_current = DateUtil.addDay(V_current, addDay); if (holidayMap.containsKey(DateUtil.dateParse(V_current, "yyyyMMdd"))) { // 是节假日 } else { // 是交易日(表示V_current日期可以返回) P_nums--; } } return V_current; } /** * 是否是交易日 * * @param current * 日期 * @return */ public static final boolean isTradeDate(Date current) { Map<String, String> holidayMap = EhCacheUtil.get(EHCACHE_HOLIDAY_DATE); if (holidayMap.containsKey(DateUtil.dateParse(current, "yyyyMMdd"))) { return false; } return true; } /** * 初使化交易日数据 * * @param holidayMap * 交易日数据 */ public static final void initTradeDate(Map<String, String> holidayMap) { EhCacheUtil.put(EHCACHE_HOLIDAY_DATE, holidayMap); } /** * 初使化交易日数据 * * @param tradeDateFilePath * 交易日文件 */ public static final void initTradeDate(String tradeDateFilePath) { try { // 测试股票 // System.out.println(DateUtil.class.getResource("/trade_dates.txt").getPath()); // String file = "/versionManager/sources/java/zj-model/integration/tools/src/main/resources/trade_dates.txt"; Set<String> holidays = new HashSet<String>(); Map<String, String> holidayMap = new HashMap<String, String>(); FileUtil.readLines(holidays, new File(tradeDateFilePath)); for (String v : holidays) { String[] vs = JavaUtil.split(v, "\t"); if (vs.length == 2) { // System.out.println(vs[0] + ":" + vs[1]); holidayMap.put(vs[0], vs[1]); } } EhCacheUtil.put(EHCACHE_HOLIDAY_DATE, holidayMap); } catch (Exception e) { log.error("初使化交易日错误"); } } /** * 取交易日 * * @param current * 日期 * @see #tradeDate(TradeDate) * @return */ @Deprecated public static final Date preTradeDate(Date current) { return preTradeDate(current, 1, true); } /** * 取交易日 * * @param current * 日期 * @see #tradeDate(TradeDate) * @return */ @Deprecated public static final Date preTradeDate(Date current, int tDay) { return preTradeDate(current, tDay, true); } /** * 取交易日 * * @param current * 日期 * @see #tradeDate(TradeDate) * @return */ @Deprecated public static final Date preTradeDate(Date current, int tDay, boolean before) { Map<String, String> holidayMap = EhCacheUtil.get(EHCACHE_HOLIDAY_DATE); if (holidayMap == null || holidayMap.size() == 0) { throw new ServiceException("未初使化交易日文件,请执行DateUtil.initTradeDate(file)"); } // 首先取上一个日期 int addDay = before ? -1 : 1; current = DateUtil.addDay(current, addDay); // 加一天 while (holidayMap.containsKey(DateUtil.dateParse(current, "yyyyMMdd"))) { // 是否是节假日 current = DateUtil.addDay(current, addDay); } if (tDay <= 1) { return current; } else { return preTradeDate(current, tDay - 1, before); } } /** * 获取交易日集合 * * @param sdate * 日期 * @param preDays * 向前取多少天 * @param diffDays * 相差多少天 * @author zhangjun * @return */ public static List<String> getTradeDates(String sdate, int preDays, int diffDays) { List<String> rdates = new ArrayList<String>(); try { Date date = DateUtil.parseDate(sdate); Map<String, String> holidayDate = EhCacheUtil.get(EHCACHE_HOLIDAY_DATE); // 相差天数 diffDays = diffDays <= 0 ? -1 : -(diffDays + 1); // 总交易日 int totalDays = -diffDays * preDays; // 相隔日期 List<String> dates = new ArrayList<String>(); loop: while (true) { while (true) { // 判断是否是节假日 if (!holidayDate.containsKey(DateUtil.dateParse(date, "yyyyMMdd"))) { // 添加交易日 dates.add(DateUtil.dateParse(date, "yyyy-MM-dd")); // 总天数减1 totalDays--; if (totalDays <= 0) { // 循环结束后-1 break loop; } } date = DateUtil.addDay(date, -1); } } // 真实的交易日 for (int i = 0; i < dates.size(); i = i - diffDays) { rdates.add(dates.get(i)); } // logger.info("-------待计算的所有交易日------------\n" + dates.size() + ":" + dates); // logger.info("-------计算相隔后的所有交易日------------\n" + rdates.size() + ":" + rdates); } catch (Exception e) { throw new ServiceException(e); } return rdates; } // =====================================================交易日====================================== /** * 日期类型 * * @author zhangjun * */ public static class DateType implements Serializable { private static final long serialVersionUID = 1L; public static int DATE_TYPE_ALL = 0; public static int DATE_TYPE_y4 = 1; public static int DATE_TYPE_y4_MM = 2; public static int DATE_TYPE_y4_MM_dd = 3; public static int DATE_TYPE_y4_MM_dd_HH = 4; public static int DATE_TYPE_y4_MM_dd_HH_mm = 5; public static int DATE_TYPE_y4_MM_dd_HH_mm_ss = 6; public static int RANGE_TYPE_y = 0; public static int RANGE_TYPE_M = 1; public static int RANGE_TYPE_d = 2; public static int RANGE_TYPE_H = 3; public static int RANGE_TYPE_m = 4; public static int RANGE_TYPE_s = 5; } /** * 星期标识1-7=>周一-周日 */ public static enum Weekday { MONDAY("1", "星期一"), TUESDAY("2", "星期二"), WEDNESDAY("3", "星期三"), THURSDAY("4", "星期四"), FRIDAY("5", "星期五"), SATURDAY("6", "星期六"), SUNDAY("7", "星期日"); private final String value; public String getValue() { return value; } private final String name; public String getName() { return name; } Weekday(String value, String name) { this.value = value; this.name = name; } // 普通方法 public static String getName(String value) { for (Weekday entity : Weekday.values()) { if (entity.getValue().equals(value)) { return entity.name; } } return "未知"; } } /** * 获取星期几 * * @param w * 星期标识1-7=>周一-周日 * @return */ public static final String getDescWeekday(int w) { switch (w) { case 1: return "星期一"; case 2: return "星期二"; case 3: return "星期三"; case 4: return "星期四"; case 5: return "星期五"; case 6: return "星期六"; case 7: return "星期日"; default: return ""; } } /** * 获取星期几 * * @param w * 星期标识0-6=>周日-周六 * @return */ public static final String getDescWeekday(String w) { return getDescWeekday(TypeUtil.Primitive.intValue(w)); } /** * 字符串转日期 * * @param dt * 日期字符串 * @return 日期对象 */ public static Date parseDate(String dt) { return parseDate(dt, DateType.DATE_TYPE_ALL); } /** * 字符串转日期 * * @param dt * 日期字符串 * @param dateType * 日期类型 * @see DateType * @return 日期对象 */ public static Date parseDate(String dt, int dateType) { Date rd = null; try { if (dt == null || dt == "") { log.warn("日期不能为:" + dt); } else { boolean isFail = false; String _val_format = "【" + dt + "】不是一个有效的日期格式\n支持日期格式如下:\n"; if (dateType == DateType.DATE_TYPE_y4) { _val_format += "【yyyy】"; } else if (dateType == DateType.DATE_TYPE_y4_MM) { _val_format += "【yyyyMM或yyyy-MM或yyyy/MM或yyyy MM】"; } else if (dateType == DateType.DATE_TYPE_y4_MM_dd) { _val_format += "【yyyyMMdd或yyyy-MM-dd或yyyy/MM/dd或yyyy MM dd】"; } else if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH) { _val_format += "【yyyyMMddhh或yyyy-MM-dd hh或yyyy/MM/dd hh或yyyy MM dd hh】"; } else if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH_mm) { _val_format += "【yyyyMMddhhmm或yyyy-MM-dd hh:mm或yyyy/MM/dd hh:mm或yyyy MM dd hh:mm】"; } else if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH_mm_ss) { _val_format += "【yyyyMMddhhmmss或yyyy-MM-dd hh:mm:ss或yyyy/MM/dd hh:mm:ss或yyyy MM dd hh:mm:ss】"; } else { dateType = DateType.DATE_TYPE_ALL; _val_format += "【yyyy】"; _val_format += "【yyyyMM或yyyy-MM或yyyy/MM或yyyy MM】"; _val_format += "【yyyyMMdd或yyyy-MM-dd或yyyy/MM/dd或yyyy MM dd】"; _val_format += "【yyyyMMddhh或yyyy-MM-dd hh或yyyy/MM/dd hh或yyyy MM dd hh】"; _val_format += "【yyyyMMddhhmm或yyyy-MM-dd hh:mm或yyyy/MM/dd hh:mm或yyyy MM dd hh:mm】"; _val_format += "【yyyyMMddhhmmss或yyyy-MM-dd hh:mm:ss或yyyy/MM/dd hh:mm:ss或yyyy MM dd hh:mm:ss】"; } String datePat = ""; datePat = "^(\\d{4})(/|-| )(\\d{1,2})(\\2)([0-9]{1,2}) (\\d{1,2}):(\\d{1,2}):(\\d{1,2})$"; Matcher mt = Pattern.compile(datePat).matcher(dt); String year = ""; String month = ""; String day = ""; String hour = ""; String minute = ""; String second = ""; if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH_mm_ss || dateType == DateType.DATE_TYPE_ALL) { year = mt.group(1); month = mt.group(3); day = mt.group(5); hour = mt.group(6); minute = mt.group(7); second = mt.group(8); } else { isFail = true; } } else { datePat = "^(\\d{14})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH_mm_ss || dateType == DateType.DATE_TYPE_ALL) { year = dt.substring(0, 4); month = dt.substring(4, 6); day = dt.substring(6, 8); hour = dt.substring(8, 10); minute = dt.substring(10, 12); second = dt.substring(12, 14); } else { isFail = true; } } else { datePat = "^(\\d{4})(/|-| )(\\d{1,2})(\\2)(\\d{1,2}) (\\d{1,2}):(\\d{1,2})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH_mm || dateType == DateType.DATE_TYPE_ALL) { year = mt.group(1); month = mt.group(3); day = mt.group(5); hour = mt.group(6); minute = mt.group(7); second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{12})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH_mm || dateType == DateType.DATE_TYPE_ALL) { year = dt.substring(0, 4); month = dt.substring(4, 6); day = dt.substring(6, 8); hour = dt.substring(8, 10); minute = dt.substring(10, 12); second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{4})(/|-| )(\\d{1,2})(\\2)(\\d{1,2}) (\\d{1,2})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH || dateType == DateType.DATE_TYPE_ALL) { year = mt.group(1); month = mt.group(3); day = mt.group(5); hour = mt.group(6); minute = "0"; second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{10})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd_HH || dateType == DateType.DATE_TYPE_ALL) { year = dt.substring(0, 4); month = dt.substring(4, 6); day = dt.substring(6, 8); hour = dt.substring(8, 10); minute = "0"; second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{4})(/|-| )(\\d{1,2})(\\2)(\\d{1,2})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd || dateType == DateType.DATE_TYPE_ALL) { year = mt.group(1); month = mt.group(3); day = mt.group(5); hour = "0"; minute = "0"; second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{8})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM_dd || dateType == DateType.DATE_TYPE_ALL) { year = dt.substring(0, 4); month = dt.substring(4, 6); day = dt.substring(6, 8); hour = "0"; minute = "0"; second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{4})(/|-| )(\\d{1,2})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM || dateType == DateType.DATE_TYPE_ALL) { year = mt.group(1); month = mt.group(3); day = "1"; hour = "0"; minute = "0"; second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{6})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4_MM || dateType == DateType.DATE_TYPE_ALL) { year = dt.substring(0, 4); month = dt.substring(4, 6); day = "1"; hour = "0"; minute = "0"; second = "0"; } else { isFail = true; } } else { datePat = "^(\\d{4})$"; mt = Pattern.compile(datePat).matcher(dt); if (mt.find()) { if (dateType == DateType.DATE_TYPE_y4 || dateType == DateType.DATE_TYPE_ALL) { year = mt.group(1); month = "1"; day = "1"; hour = "0"; minute = "0"; second = "0"; } else { isFail = true; } } else { _val_format = "【" + dt + "】不是一个有效的日期格式"; isFail = true; } } } } } } } } } } } if (isFail) { log.warn(_val_format); } else { int iyear = Integer.parseInt(year); int imonth = Integer.parseInt(month); int iday = Integer.parseInt(day); int ihour = Integer.parseInt(hour); int iminute = Integer.parseInt(minute); int isecond = Integer.parseInt(second); if (iyear < 1 || iyear > 9999) { _val_format = "年份必须在0001-9999之间"; isFail = true; } if (imonth < 1 || imonth > 12) { _val_format = "月份必须在01-12之间"; isFail = true; } if (iday < 1 || iday > 31) { _val_format = "天数必须在01-31之间"; isFail = true; } if ((imonth == 4 || imonth == 6 || imonth == 9 || imonth == 11) && iday == 31) { _val_format = month + "月不能有31天!"; isFail = true; } if (imonth == 2) { boolean isleap = (iyear % 4 == 0 && iyear % 100 != 0) || iyear % 400 == 0; if (isleap) { if (iday > 29) { _val_format = "闰年[" + year + "]年的2月不能有[" + day + "]天!"; isFail = true; } } else { if (iday > 28) { _val_format = "平年[" + year + "]年的2月不能有[" + day + "]天!"; isFail = true; } } } if (ihour < 0 || ihour > 23) { _val_format = "小时必须在00-23之间"; isFail = true; } if (iminute < 0 || iminute > 59) { _val_format = "分钟必须在00-59之间"; isFail = true; } if (isecond < 0 || isecond > 59) { _val_format = "秒钟必须在00-59之间"; isFail = true; } if (isFail) { log.warn(_val_format); } else { // //("调试字符串如下【开始】\n" + sb.toString() + "\n调试字符串如下【结束】"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(0); calendar.set(iyear, imonth - 1, iday, ihour, iminute, isecond); rd = calendar.getTime(); } } } } catch (Exception e) { rd = null; log.error(e.getMessage()); } return rd; } /** * 日期解析字符串 * * @param odt * 日期对象 * @return 返回格式化后的日期字符串,如果出错返回当前日期对象 */ public static String dateParse(Object odt) { return dateParse(odt, null); } /** * 日期解析字符串 * * @param odt * 日期对象 * @param partten * 日期格式 * <p> * yyyy年MM月dd日HH时mm分ss秒SSS毫秒p(1-7=>周一-周日)w x q季度 * </p> * @return 返回格式化后的日期字符串,如果出错返回当前日期对象 */ public static String dateParse(Object odt, String partten) { try { if (odt == null) return ""; Date dt = null; if (odt instanceof Date) { dt = (Date) odt; } else if (odt instanceof Timestamp) { Timestamp ts = (Timestamp) odt; dt = new Date(ts.getTime()); } else if (odt instanceof Calendar) { Calendar cal = (Calendar) odt; dt = cal.getTime(); } else if (odt instanceof String) { dt = parseDate(String.valueOf(odt)); if (dt == null) { log.error("无效的日期:" + odt); return ""; } } else { log.error("无效的日期:" + odt); return String.valueOf(odt); } return getParseDt(dt, partten); } catch (Exception e) { log.error(e.getMessage()); return String.valueOf(odt); } } /** * 日期解析字符串 * * @param dt * 日期对象 * @param partten * 日期格式 * <p> * yyyy年MM月dd日HH时mm分ss秒SSS毫秒p(1-7=>周一-周日)w x q季度 * </p> * @return 返回格式化后的日期字符串,如果出错返回当前日期对象 */ public static String getParseDt(Date dt, String partten) { if (dt == null) return ""; if (partten == null || "".equals(partten)) { partten = "yyyy年MM月dd日HH时mm分ss秒SSS毫秒p(1-7=>周一-周日)w x q季度"; } Calendar cal = Calendar.getInstance(); cal.setTime(dt); String year = "" + cal.get(Calendar.YEAR); String month = "" + (cal.get(Calendar.MONTH) + 1); String day = "" + cal.get(Calendar.DATE); String hour = "" + cal.get(Calendar.HOUR_OF_DAY); String minute = "" + cal.get(Calendar.MINUTE); String second = "" + cal.get(Calendar.SECOND); String millisecond = "" + cal.get(Calendar.MILLISECOND); // 星期标识【0-6=>周日-周六】=>返回【1-7=>周一-周日】 int week_of_month = cal.get(Calendar.DAY_OF_WEEK) - 1; // 星期值 String ws = ""; switch (week_of_month) { case 1: ws += "1"; break; case 2: ws += "2"; break; case 3: ws += "3"; break; case 4: ws += "4"; break; case 5: ws += "5"; break; case 6: ws += "6"; break; case 0: ws += "7"; break; default: ws = ""; break; } // 上下午 int r = cal.get(Calendar.AM_PM); String ap = ""; if (r == Calendar.AM) { ap = "上午"; } if (r == Calendar.PM) { ap = "下午"; } // 季度值 int tempMonth = TypeUtil.Primitive.intValue(month); // quarter季度 String q = ""; if (tempMonth >= 1 && tempMonth <= 3) { q = "1"; } else if (tempMonth >= 4 && tempMonth <= 6) { q = "2"; } else if (tempMonth >= 7 && tempMonth <= 9) { q = "3"; } else if (tempMonth >= 10 && tempMonth <= 12) { q = "4"; } String matStr = ""; // 替换4位年 matStr = "(y|Y){4}"; Matcher mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(year, "0", 4)); // 替换2位月 matStr = "M{2}"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(month, "0", 2)); // 替换季度 matStr = "(q|Q)"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(q); // 替换2位天 matStr = "d{2}"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(day, "0", 2)); // 替换2位小时 matStr = "(h|H){2}(24)?"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(hour, "0", 2)); // 替换2位分 matStr = "m{2}"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(minute, "0", 2)); // 替换2位秒 matStr = "s{2}"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(second, "0", 2)); // 替换3位毫秒 matStr = "S{3}"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR(millisecond, "0", 3)); // 替换星期 matStr = "w|W"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(ws); // 替换星期 matStr = "x|X"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(getDescWeekday(ws)); // 替换上下午 matStr = "p|P"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(ap); // 替换2位年 matStr = "(y|Y){2}"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(year.length() > 2 ? year.substring(year.length() - 2, year.length()) : year); // 替换1位月 matStr = "M"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(month); // 替换1位天 matStr = "d"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(day); // 替换1位小时 matStr = "(h|H){1}(12)?"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(addForLR((Integer.parseInt(hour) > 12 ? "" + Math.abs(Integer.parseInt(hour) - 12) : hour), "0", 2)); // matStr = "(h|H)12"; // mt = Pattern.compile(matStr).matcher(partten); // partten = mt.replaceAll(Integer.parseInt(hour) > 12 ? "" + Math.abs(Integer.parseInt(hour) - 12) : hour); // matStr = "(h|H)24"; // mt = Pattern.compile(matStr).matcher(partten); // partten = mt.replaceAll(hour); // 替换1位分 matStr = "m"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(minute); // 替换1位秒 matStr = "s"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(second); // 替换1位毫秒 matStr = "S"; mt = Pattern.compile(matStr).matcher(partten); partten = mt.replaceAll(millisecond); // 最终结果 return partten; } /** * 数字前补0可以补"0"也可以补"" * * @param oldStr * 旧字符串 * @param addStr * 添加字符串 * @param strLength * 字符长度 * @param isLeft * <p> * true:左补字符 * </p> * <p> * false:右补字符 * </p> * @author zhangjun * @return 重组后的数据 */ public static String addForLR(String oldStr, String addStr, int strLength, boolean isLeft) { if (oldStr == null || addStr == null) return oldStr; int strLen = oldStr.length(); if (strLen < strLength) { while (strLen < strLength) { StringBuffer sb = new StringBuffer(); if (isLeft) { sb.append(addStr).append(oldStr); } else { sb.append(oldStr).append(addStr); } oldStr = sb.toString(); strLen = oldStr.length(); } } return oldStr; } /** * 数字前补0可以补"0"也可以补"" * * @param oldStr * 旧字符串 * @param addStr * 添加字符串 * @param strLength * 字符长度 * @author zhangjun * @return 重组后的数据 */ public static String addForLR(String oldStr, String addStr, int strLength) { return addForLR(oldStr, addStr, strLength, true); } /** * 计算日期范围 * * @param startTime * 开始日期对象 * @param endTime * 结束日期对象 * @param rangeType * 范围类型 * @param ymdhms * 年月日时分秒 * @param dateType * 日期类型 */ public static String dateRangeFlg(Object startTime, Object endTime, int rangeType, int ymdhms, int dateType) { String sstartTime = startTime == null ? "" : String.valueOf(startTime); String sendTime = endTime == null ? "" : String.valueOf(endTime); String rtn_1 = "1"; String rtn_2 = "2"; String rtn_3 = "3"; String rtn_4 = "4"; String rtn_5 = "5"; String rtn_6 = "6"; try { if ("".equals(sstartTime)) { return rtn_4; } if ("".equals(sendTime)) { return rtn_5; } Date checktime1 = null; Date checktime2 = null; if (startTime instanceof Date) { checktime1 = (Date) startTime; } else { checktime1 = parseDate(sstartTime, dateType); } if (checktime1 == null) { return rtn_4; } if (endTime instanceof Date) { checktime2 = (Date) endTime; } else { checktime2 = parseDate(sendTime, dateType); } if (checktime2 == null) { return rtn_5; } if (startTime == "" || endTime == "") return ""; Calendar cal1 = Calendar.getInstance(); cal1.setTimeInMillis(0); cal1.setTime(checktime1); Calendar cal2 = Calendar.getInstance(); cal2.setTimeInMillis(0); cal2.setTime(checktime2); long flg = cal2.getTimeInMillis() - cal1.getTimeInMillis(); if (flg < 0) { // //("开始时间不能大于结束时间!"); return rtn_6; } if (rangeType == DateType.RANGE_TYPE_y) { cal1.set(Calendar.YEAR, cal1.get(Calendar.YEAR) + ymdhms); // v_typeMsg = "年"; } else if (rangeType == DateType.RANGE_TYPE_M) { cal1.set(Calendar.MONTH, cal1.get(Calendar.MONTH) + ymdhms); // v_typeMsg = "个月"; } else if (rangeType == DateType.RANGE_TYPE_d) { cal1.set(Calendar.DATE, cal1.get(Calendar.DATE) + ymdhms); // v_typeMsg = "天"; } else if (rangeType == DateType.RANGE_TYPE_H) { cal1.set(Calendar.HOUR_OF_DAY, cal1.get(Calendar.HOUR_OF_DAY) + ymdhms); // v_typeMsg = "小时"; } else if (rangeType == DateType.RANGE_TYPE_m) { cal1.set(Calendar.MINUTE, cal1.get(Calendar.MINUTE) + ymdhms); // v_typeMsg = "分钟"; } else if (rangeType == DateType.RANGE_TYPE_s) { cal1.set(Calendar.SECOND, cal1.get(Calendar.SECOND) + ymdhms); // v_typeMsg = "秒钟"; } else { // //("类型值不正确,请看下面提示\ny:年,m1:月,d:日,h:时,m2:分,s:秒"); return rtn_3; } flg = cal2.getTimeInMillis() - cal1.getTimeInMillis(); if (flg > 0) { // //("开始时间和结束时间相差不能超过" + ymdhms + v_typeMsg + "!"); return rtn_1; } else { return rtn_2; } } catch (Exception e) { return rtn_3; } } /** * Calendar 转换为 Date * * @return date日期 */ public static Date calToDate() { // (1) Calendar转化为Date Calendar cal = Calendar.getInstance(); return calToDate(cal); } /** * Calendar 转换为 Date * * @param cal * Calendar日期 * @return date日期 */ public static Date calToDate(Calendar cal) { // (1) Calendar转化为Date Date date = cal.getTime(); return date; } /** * Date 转换为 Calendar * * @return Calendar日期 */ public static Calendar dateToCal() { // (2) Date转化为Calendar Date date = new Date(); return dateToCal(date); } /** * Date 转换为 Calendar * * @param date * date日期 * @return Calendar日期 */ public static Calendar dateToCal(Date date) { // (2) Date转化为Calendar Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } /** * 相差x年又y天 * * @param sd * 开始日期 * @param ed * 结束日期 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return * */ public static String diffYearAndDay(Date startDate, Date endDate) { if (startDate == null || endDate == null) { return "?天"; } long diffDate = DateUtil.diffDay(startDate, endDate); int year = 0; while (diffDate > 365) { diffDate -= 365; year++; } if (year > 0) { return year + "年又" + diffDate + "天"; } else { return diffDate + "天"; } } /** * 相差日-秒 * * @param sd * 开始日期 * @param ed * 结束日期 * @return 返回值为:{天, 时, 分, 秒} */ public static long[] diffDayToSecond(Date sd, Date ed) { Date newSd = new Date(sd.getTime()); Date newEd = new Date(ed.getTime()); long diff = newEd.getTime() - newSd.getTime(); long day = 0; long hour = 0; long min = 0; long sec = 0; day = diff / (24 * 60 * 60 * 1000); hour = (diff / (60 * 60 * 1000) - day * 24); min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); long[] times = { day, hour, min, sec }; return times; } /** * 相差日 * * @param sd * 开始日期 * @param ed * 结束日期 * @return 相差值 */ public static long diffDay(Date sd, Date ed) { Date newSd = new Date(sd.getTime()); Date newEd = new Date(ed.getTime()); long diff = newEd.getTime() - newSd.getTime(); return diff / (24 * 60 * 60 * 1000); } /** * 加日 * * @param d * 日期 * @param day * 天数 * @return 计算后的日期 */ public static Date addDay(Date d, int day) { Date newD = new Date(d.getTime()); newD.setTime(newD.getTime() + (long) day * 86400000L); return newD; } /** * 加月 * * @param d * 日期 * @param month * 月数 * @return 计算后的日期 */ public static Date addMonth(Date d, int month) { Date newD = new Date(d.getTime()); GregorianCalendar gval = new GregorianCalendar(); gval.setTime(newD); gval.add(2, month); newD.setTime(gval.getTime().getTime()); return newD; } /** * 加年 * * @param d * 日期 * @param year * 年数 * @return 计算后的日期 */ public static Date addYear(Date d, int year) { Date newD = new Date(d.getTime()); GregorianCalendar gval = new GregorianCalendar(); gval.setTime(newD); gval.add(1, year); newD.setTime(gval.getTime().getTime()); return newD; } /** * 相差时 * * @param sd * 开始日期 * @param ed * 结束日期 * @return 相差值 */ public static long diffHour(Date sd, Date ed) { Date newSd = new Date(sd.getTime()); Date newEd = new Date(ed.getTime()); long diff = newEd.getTime() - newSd.getTime(); return diff / (60 * 60 * 1000); } /** * 加小时 * * @param d * 日期 * @param hour * 小时数 * @return 计算后的日期 */ public static Date addHour(Date d, int hour) { Date newD = new Date(d.getTime()); newD.setTime(newD.getTime() + (long) hour * 3600000L); return newD; } /** * 相差分 * * @param sd * 开始日期 * @param ed * 结束日期 * @return 相差值 */ public static long diffMinute(Date sd, Date ed) { Date newSd = new Date(sd.getTime()); Date newEd = new Date(ed.getTime()); long diff = newEd.getTime() - newSd.getTime(); return diff / (60 * 1000); } /** * 加分 * * @param d * 日期 * @param minute * 分数 * @return 计算后的日期 */ public static Date addMinute(Date d, int minute) { Date newD = new Date(d.getTime()); newD.setTime(newD.getTime() + (long) minute * 60000L); return newD; } /** * 相差秒 * * @param sd * 开始日期 * @param ed * 结束日期 * @return 相差值 */ public static long diffSecond(Date sd, Date ed) { Date newSd = new Date(sd.getTime()); Date newEd = new Date(ed.getTime()); long diff = newEd.getTime() - newSd.getTime(); return diff / (1000); } /** * 加秒 * * @param d * 日期 * @param second * 秒数 * @return 计算后的日期 */ public static Date addSecond(Date d, int second) { Date newD = new Date(d.getTime()); newD.setTime(newD.getTime() + (long) second * 1000L); return newD; } /** * 加毫秒 * * @param d * 日期 * @param minSecond * 毫秒数 * @return 计算后的日期 */ public static Date addMinSecond(Date d, long minSecond) { Date newD = new Date(d.getTime()); newD.setTime(newD.getTime() + minSecond * 1L); return newD; } /** * 将元数据前补零,补后的总长度为指定的长度,以字符串的形式返回 * * @param sourceData * 源数据 * @param formatLength * 长度 * @return 重组后的数据 */ public static String frontCompWithZore(int sourceData, int formatLength) { /* * 0 指前面补充零 formatLength 字符总长度为 formatLength d 代表为正数。 */ String newString = String.format("%0" + formatLength + "d", sourceData); return newString; } /** * 毫秒转时分秒毫秒 * * @param millis * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @return */ public static Map<String, Integer> millisToHmsS(int millis) { Map<String, Integer> values = new HashMap<String, Integer>(); // 时 int h = 0; // 分 int m = 0; // 秒 int s = 0; // 毫秒 int S = 0; if (millis <= 1000) { S = millis; } else { int second = millis / 1000; if (millis % 1000 != 0) { // 毫秒数 S = millis % 1000; } if (second > 3600) { // 如果大于3600秒 int temp = second % 3600; h = second / 3600; if (temp != 0) { if (temp > 60) { m = temp / 60; if (temp % 60 != 0) { s = temp % 60; } } else { s = temp; } } } else { // 如果小于等于3600秒 m = second / 60; if (second % 60 != 0) { s = second % 60; } } } // System.out.println(h + "时" + m + "分" + s + "秒" + S + "毫秒"); values.put("h", h); values.put("m", m); values.put("s", s); values.put("S", S); return values; } }
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com