下面是java的各种工具,包括获取时间和时间比较,检验集合和字符串是否为空和长度大小等等
1 import java.io.BufferedReader;
2 import java.io.File;
3 import java.io.OutputStream;
4 import java.io.Reader;
5 import java.io.UnsupportedEncodingException;
6 import java.math.BigDecimal;
7 import java.text.DateFormat;
8 import java.text.DecimalFormat;
9 import java.text.ParseException;
10 import java.text.SimpleDateFormat;
11 import java.util.ArrayList;
12 import java.util.Calendar;
13 import java.util.Collection;
14 import java.util.Date;
15 import java.util.GregorianCalendar;
16 import java.util.List;
17 import java.util.Map;
18
19 import jxl.Workbook;
20 import jxl.write.Label;
21 import jxl.write.WritableCellFormat;
22 import jxl.write.WritableFont;
23 import jxl.write.WritableSheet;
24 import jxl.write.WritableWorkbook;
25
26 import org.apache.commons.io.FilenameUtils;
27 import org.apache.commons.lang.CharUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang.time.DateFormatUtils;
30 import org.apache.commons.validator.GenericValidator;
31
32 import sun.misc.BASE64Decoder;
33
34 import com.xmld.server.constant.GeneralConstant;
35 import com.xmld.server.exception.ServiceException;
36
37 /**
38 * 通用的工具类
39 */
40 public final class GeneralUtils
41 {
42
43 private GeneralUtils()
44 {
45
46 }
47
48 /**
49 * 判断对象是否为null , 为null返回true,否则返回false
50 * @param obj 被判断的对象
51 * @return boolean
52 */
53 public static boolean isNull(Object obj)
54 {
55 return (null == obj) ? true : false;
56 }
57
58 /**
59 * 判断对象是否为null , 为null返回false,否则返回true
60 *
61 * @param obj 被判断的对象
62 * @return boolean
63 */
64 public static boolean isNotNull(Object obj)
65 {
66 return !isNull(obj);
67 }
68
69 /**
70 * 判断字符串是否为null或者0长度,字符串在判断长度时,先去除前后的空格,空或者0长度返回true,否则返回false
71 *
72 * @param str 被判断的字符串
73
74 * @return boolean
75 */
76 public static boolean isNullOrZeroLenght(String str)
77 {
78 return GenericValidator.isBlankOrNull(str);
79 }
80
81 /**
82 * 判断字符串是否为null或者0长度,字符串在判断长度时,先去除前后的空格,空或者0长度返回false,否则返回true
83 *
84 * @param str 被判断的字符串
85
86 * @return boolean
87 */
88 public static boolean isNotNullOrZeroLenght(String str)
89 {
90 return !isNullOrZeroLenght(str);
91 }
92
93 /**
94 * 判断str数组是否为null或者0长度,只要有一个空或者0长度返回false, 否则返回true
95 *
96 * @param str String 字符数组
97 * @return boolean
98 * @author huanghui
99 * @see [类、类#方法、类#成员]
100 */
101 public static boolean isNotNullOrZeroLenght(String... str)
102 {
103 for (String s : str)
104 {
105 if (isNullOrZeroLenght(s))
106 {
107 return false;
108 }
109 }
110 return true;
111 }
112
113 /**
114 * 判断str数组是否为null或者0长度,只要有一个空或者0长度返回true, 否则返回false
115 *
116 * @param str String 字符数组
117 * @return boolean
118 * @author huanghui
119 * @see [类、类#方法、类#成员]
120 */
121 public static boolean isNullOrZeroLenght(String... str)
122 {
123 return !isNotNullOrZeroLenght(str);
124 }
125
126 /**
127 * 判断集合对象是否为null或者0大小 , 为空或0大小返回true ,否则返回false
128 *
129 * @param c collection 集合接口
130 * @return boolean 布尔值
131
132 * @author huanghui
133 * @see [类、类#方法、类#成员]
134 */
135 public static boolean isNullOrZeroSize(Collection<? extends Object> c)
136 {
137 return isNull(c) || c.isEmpty();
138 }
139
140 /**
141 * 判断集合对象是否为null或者0大小 , 为空或0大小返回false, 否则返回true
142 *
143 * @param c collection 集合接口
144 * @return boolean 布尔值
145
146 * @author huanghui
147 * @see [类、类#方法、类#成员]
148 */
149 public static boolean isNotNullOrZeroSize(Collection<? extends Object> c)
150 {
151 return !isNullOrZeroSize(c);
152 }
153
154 /**
155 * 判断数字类型是否为null或者0,如果是返回true,否则返回false
156 *
157 * @param number 被判断的数字
158 * @return boolean
159 */
160 public static boolean isNullOrZero(Number number)
161 {
162 if (GeneralUtils.isNotNull(number))
163 {
164 return (number.doubleValue() != 0) ? false : true;
165 }
166 return true;
167 }
168
169 /**
170 * 判断数字类型是否不为null或者0,如果是返回true,否则返回false
171 *
172 * @param number 被判断的数字
173 * @return boolean
174 */
175 public static boolean isNotNullOrZero(Number number)
176 {
177 return !isNullOrZero(number);
178 }
179
180 /**
181 * 将java.util.Date类型转化位String类型
182 *
183 * @param date 要转换的时间
184 * @param format 时间格式
185 * @return 如果转换成功,返回指定格式字符串,如果转换失败,返回null
186 */
187 public static String date2String(Date date, String format)
188 {
189 if (GeneralUtils.isNull(date) || GeneralUtils.isNull(format))
190 {
191 return null;
192 }
193
194 return DateFormatUtils.format(date, format);
195 }
196
197 /**
198 * 将字符串时间转换成java.util.Date类型
199 * @param str 要转换的字符串
200 * @param format 时间格式
201 * @return 如果转换失败,返回null
202 */
203 public static Date string2Date(String str, String format)
204 {
205 if (GeneralUtils.isNull(str) || GeneralUtils.isNull(format))
206 {
207 return null;
208 }
209
210 // 定义日期/时间格式
211 SimpleDateFormat sdf = new SimpleDateFormat(format);
212 Date date;
213
214 try
215 {
216 // 转换日期/时间格式
217 date = sdf.parse(str);
218 // 判断转换前后时间是否一致
219
220 if (!str.equals(sdf.format(date)))
221 {
222 date = null;
223 }
224 }
225 catch (ParseException e)
226 {
227 date = null;
228 }
229
230 return date;
231 }
232
233 /**
234 * 将字符串时间转换时间格式
235 * @param str 要转换的字符串
236 * @param formatF 初始时间格式
237 * @param formatT 目标时间格式
238 * @return 如果转换失败,返回null
239 */
240 public static String String2String(String str, String formatF, String formatT)
241 {
242 return date2String(string2Date(str, formatF), formatT);
243 }
244
245 /**
246 * 验证日期/时间格式
247 * @param dateStr 待验证的字符串
248 * @param format 类型
249 * @return 是返回ture,否则返回false
250 */
251 public static boolean isDateTime(String dateStr, String format)
252 {
253 return GenericValidator.isDate(dateStr, format, true);
254 }
255
256 /**
257 * 判断字符串长度,范围包含min和max的值
258
259 *
260 * @param str String
261 * @param min 最小范围
262
263 * @param max 最大范围
264
265 * @return boolean
266 */
267 public static boolean isInRange(String str, int min, int max)
268 {
269 if (GeneralUtils.isNull(str))
270 {
271 return false;
272 }
273
274 try
275 {
276 int len = str.trim().getBytes(GeneralConstant.CHARACTER_CODING).length;
277 return GenericValidator.isInRange(len, min, max);
278 }
279 catch (UnsupportedEncodingException e)
280 {
281 return false;
282 }
283 }
284
285
286 /**
287 * 判断字符串是否超过最大长度
288
289 * @param str String
290 * @param max 最大长度
291
292 * @return boolean
293 */
294 public static boolean maxLength(String str, int max)
295 {
296 return isInRange(str, 0, max);
297 }
298
299 /**
300 * 判断字符串是否低于最小长度
301
302 * @param str String
303 * @param min 最小长度
304
305 * @return boolean
306 */
307 public static boolean minLength(String str, int min)
308 {
309 return isInRange(str, min, Integer.MAX_VALUE);
310 }
311
312 /**
313 * 获取目录在系统中的绝对路径
314 * @param path 路径
315 * @return Sting
316 */
317 public static String getAbsolutePath(String path)
318 {
319 // 如果路进为null,则认为时当前目录
320
321 path = (GeneralUtils.isNull(path)) ? "" : path;
322 File file = new File(path);
323
324 // 获取完整路径
325 return FilenameUtils.separatorsToUnix(file.getAbsolutePath());
326 }
327
328 /**
329 * 将字符串首字符待大写
330 * @param str 源字符串
331 * @return 首字符大写后的字符串
332 * @see [类、类#方法、类#成员]
333 */
334 public static String firstCharUpper(String str)
335 {
336 char firstChar = CharUtils.toChar(str);
337 String upFirstChar = StringUtils.upperCase(String.valueOf(firstChar));
338 return StringUtils.replaceOnce(str, String.valueOf(firstChar), upFirstChar);
339 }
340
341 /**
342 * Object - > String
343 * @param obj 对象参数
344 * @return String 字符串
345 */
346 public static String object2String(Object obj)
347 {
348 if (isNull(obj))
349 {
350 return "";
351 }
352 else
353 {
354 return obj.toString();
355 }
356 }
357
358 /**
359 * 返回当前的时间戳
360 * @return 时间戳
361 */
362 public static String getCurrentTimeStamp()
363 {
364 return Long.toString(System.currentTimeMillis() / 1000);
365 }
366
367 /**
368 * 返回当前时间戳
369 * @param pattern 默认为:yyyyMMddHHmmss
370 * @return string 时间字符串
371 */
372 public static String getCurrentTimeStamp(String pattern)
373 {
374 if (isNullOrZeroLenght(pattern))
375 {
376 pattern = GeneralConstant.DATETIME_14;
377 }
378 Date date = new Date(System.currentTimeMillis());
379 return date2String(date, pattern);
380 }
381
382 /**
383 * 返回昨天的日期
384 * @param pattern
385 * @return
386 */
387 public static String getNextDay(String pattern) {
388 if (isNullOrZeroLenght(pattern))
389 {
390 pattern = GeneralConstant.DATETIME_14;
391 }
392 Calendar calendar = Calendar.getInstance();
393 Date dNow = new Date();
394 calendar.setTime(dNow);
395 calendar.add(Calendar.DAY_OF_MONTH, -1);
396 dNow = calendar.getTime();
397 return date2String(dNow, pattern);
398 }
399 /**
400 * 返回当前时间戳
401 * @return 17位时间戳表示
402 */
403 public static String getCurrentTimeStamp17Bit()
404 {
405 Date date = new Date(System.currentTimeMillis());
406 return date2String(date, GeneralConstant.DATETIME_17);
407 }
408
409 /**
410 * 返回当前时间戳
411 * @return 12位时间戳表示
412 */
413 public static String getCurrentTimeStamp12Bit()
414 {
415 Date date = new Date(System.currentTimeMillis());
416 return date2String(date, GeneralConstant.DATETIME_12_A);
417 }
418
419 /**
420 * 根据格式和间隔时间返回系统当前日期N天前或者N天后的日期
421 * @param pattan 格式化时间
422 * @param days 间隔时间 正数代表之后的日期,负数代表之前的日期
423 * @return
424 * @see [类、类#方法、类#成员]
425 */
426 public static String getNSystemTime(String pattan, int days)
427 {
428 GregorianCalendar currentDate = new GregorianCalendar();
429 currentDate.add(GregorianCalendar.DATE, days);
430 Date date = currentDate.getTime();
431 SimpleDateFormat df = new SimpleDateFormat(pattan);
432 String preDay = df.format(date);
433 return preDay;
434 }
435
436 /**
437 * 根据格式化字符获取时间
438 * @param dateStr 字符串时间
439 * @param pattern 格式化方式
440 * @return Date Date
441 */
442 public static Date getDate(String dateStr, String pattern)
443 {
444 Date date = null;
445 try
446 {
447 date = new SimpleDateFormat(pattern).parse(dateStr);
448 }
449 catch (ParseException e)
450 {
451 return null;
452 }
453 return date;
454 }
455
456 /**
457 * 拼装文件路径
458 * @param basePath 文件路径
459 * @param fullFilenameToAdd 文件名或带部分路径的文件名
460 * @return 返回处理后的字符串
461 */
462 public static String filePathConcat(String basePath, String fullFilenameToAdd)
463 {
464 String path1 = FilenameUtils.separatorsToUnix(GeneralUtils.isNull(basePath) ? "" : basePath);
465 String path2 = FilenameUtils.separatorsToUnix(GeneralUtils.isNull(fullFilenameToAdd) ? "" : fullFilenameToAdd);
466
467 if (GeneralUtils.isNullOrZeroLenght(path1))
468 {
469 return path2;
470 }
471
472 if ((path1.length() - 1) == StringUtils.lastIndexOf(path1, GeneralConstant.SEPARATOR))
473 {
474 path1 = StringUtils.substring(path1, 0, path1.length() - 1);
475 }
476
477 if (0 == StringUtils.indexOf(path2, GeneralConstant.SEPARATOR))
478 {
479 path2 = StringUtils.substring(path2, 1);
480 }
481
482 return path1 + GeneralConstant.SEPARATOR + path2;
483
484 }
485
486 /**
487 * 删除文件
488 * @param filePathname 文件路径
489 * @throws ServiceException 业务异常
490 */
491 public static void deleteFile(String filePathname)
492 throws ServiceException
493 {
494 // 如果路径为空或空字符串,直接返回不做处理
495 if (isNullOrZeroLenght(filePathname))
496 {
497 return;
498 }
499
500 // 定义删除的文件
501
502 File fileObject = new File(filePathname);
503
504 // 如果文件不存在,直接返回
505 if (!fileObject.exists() || !fileObject.isFile())
506 {
507 return;
508 }
509
510 // 如果删除文件失败,则抛出异常
511 if (!fileObject.delete())
512 {
513 throw new ServiceException("");
514 }
515 }
516
517 /**
518 * 将以特定字符作为分隔符的字符串转换为Set集合
519 * @param strToBeConverted - 待转换的字符串
520 * @param separator - 分隔符
521 * @return - 转换后的列表对象
522 */
523 public static List<String> splitStringUseSpecifiedSeparator(String strToBeConverted, String separator)
524 {
525 // 转换后集合对象,初始设置为空。
526
527 List<String> resultList = new ArrayList<String>();
528
529 // 原始字符串为NULL或者为空,直接返回空Set
530 if (StringUtils.isEmpty(strToBeConverted))
531 {
532 return resultList;
533 }
534
535 // 分隔符为NUlL或者空,返回只包含原始字符串的Set
536 if (StringUtils.isEmpty(separator))
537 {
538 resultList.add(strToBeConverted);
539 }
540
541 // 按照指定分隔符拆分字符串
542 String[] arrayString = strToBeConverted.split(separator);
543
544 // 遍历数组,组装到Set集合中。方便调用程序处理。
545
546 for (String str : arrayString)
547 {
548 resultList.add(str);
549 }
550
551 return resultList;
552 }
553
554 /**
555 * 生成EXCEL
556 * @param filePath 文件路径
557 * @param xlContents 需要生成的内容
558 * @param cellConfig 配置
559 * @see [类、类#方法、类#成员]
560 */
561 public static void createExcel(String filePath, List<Object> xlContents, int[] cellConfig)
562 {
563 // String targetDirectory = ServletActionContext.getServletContext().getRealPath(filePath);
564 File f = new File(filePath);
565 int[] widthConfig = new int[cellConfig.length];
566 int widthTemp = 0;
567
568 try
569 {
570 WritableWorkbook book = Workbook.createWorkbook(f);
571 WritableSheet sheet = book.createSheet("sheet", 0);
572 // //保护
573 // sheet.getSettings().setProtected(true);
574 // //保护密码
575 // sheet.getSettings().setPassword("xmld");
576 //冻结标题
577 sheet.getSettings().setVerticalFreeze(1);
578
579 for (int i = 0; i < xlContents.size(); i++)
580 {
581 Object iContents = xlContents.get(i);
582
583 if (iContents instanceof String[])
584 {
585 for (int j = 0; j < ((String[])iContents).length; j++)
586 {
587 WritableCellFormat wcf = new WritableCellFormat();
588 wcf.setAlignment(jxl.format.Alignment.CENTRE);
589
590 Label label = new Label(j, i, ((String[])iContents)[j], wcf);
591 sheet.addCell(label);
592
593 widthTemp = String.valueOf(((String[])iContents)[j]).getBytes("GBK").length + 1;
594 if (widthTemp > widthConfig[j])
595 {
596 widthConfig[j] = widthTemp;
597 }
598 }
599 }
600 else
601 {
602 for (int j = 0; j < ((List<?>)iContents).size(); j++)
603 {
604 Object obj = ((List<?>)iContents).get(j);
605
606 WritableCellFormat wcf = new WritableCellFormat();
607 if (cellConfig[j] == 1)
608 {
609 wcf.setLocked(true);
610 }
611 else
612 {
613 wcf.setLocked(false);
614 }
615
616 if (obj instanceof Double)
617 {
618 jxl.write.Number number = new jxl.write.Number(j, i, (Double)obj, wcf);
619 sheet.addCell(number);
620
621 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
622 if (widthTemp > widthConfig[j])
623 {
624 widthConfig[j] = widthTemp;
625 }
626 }
627 else if (obj instanceof Integer)
628 {
629 jxl.write.Number number = new jxl.write.Number(j, i, (Integer)obj, wcf);
630 sheet.addCell(number);
631
632 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
633 if (widthTemp > widthConfig[j])
634 {
635 widthConfig[j] = widthTemp;
636 }
637 }
638 else if (obj instanceof Long)
639 {
640 jxl.write.Number number = new jxl.write.Number(j, i, (Long)obj, wcf);
641 sheet.addCell(number);
642
643 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
644 if (widthTemp > widthConfig[j])
645 {
646 widthConfig[j] = widthTemp;
647 }
648 }
649 else
650 {
651 Label label = new Label(j, i, (String)obj, wcf);
652 sheet.addCell(label);
653
654 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
655 if (widthTemp > widthConfig[j])
656 {
657 widthConfig[j] = widthTemp;
658 }
659 }
660 }
661 }
662 }
663 for (int i = 0; i < widthConfig.length; i++)
664 {
665 sheet.setColumnView(i, widthConfig[i]);
666 //System.out.println(widthConfig[i]);
667 }
668
669 book.write();
670 book.close();
671 }
672 catch (Exception e)
673 {
674 e.printStackTrace();
675 }
676 }
677
678 /**
679 *
680 * 生成Excel
681 * 同时写入os中
682 * @param os
683 * @param xlContents 需要生成的内容
684 * @param cellConfig 配置
685 * @param totalMoney 总计
686 * @param param 备份参数
687 * @see [类、类#方法、类#成员]
688 */
689 public static void createExcelAndRet0utDataStream(OutputStream os, List<Object> xlContents, int[] cellConfig,
690 Double totalMoney, String param)
691 {
692
693 int[] widthConfig = new int[cellConfig.length];
694 int widthTemp = 0;
695 try
696 {
697 WritableWorkbook book = Workbook.createWorkbook(os);
698 WritableSheet sheet = book.createSheet("sheet", 0);
699 //保护
700 sheet.getSettings().setProtected(true);
701 //保护密码
702 sheet.getSettings().setPassword("linkage");
703 //冻结标题
704 sheet.getSettings().setVerticalFreeze(1);
705
706 for (int i = 0; i < xlContents.size(); i++)
707 {
708 Object iContents = xlContents.get(i);
709
710 if (iContents instanceof String[])
711 {
712 for (int j = 0; j < ((String[])iContents).length; j++)
713 {
714 WritableCellFormat wcf = new WritableCellFormat();
715 wcf.setAlignment(jxl.format.Alignment.CENTRE);
716
717 Label label = new Label(j, i, ((String[])iContents)[j], wcf);
718 sheet.addCell(label);
719
720 widthTemp = String.valueOf(((String[])iContents)[j]).getBytes("GBK").length + 1;
721 if (widthTemp > widthConfig[j])
722 {
723 widthConfig[j] = widthTemp;
724 }
725 }
726 }
727 else
728 {
729 for (int j = 0; j < ((List<?>)iContents).size(); j++)
730 {
731 Object obj = ((List<?>)iContents).get(j);
732
733 WritableCellFormat wcf = new WritableCellFormat();
734 if (cellConfig[j] == 1)
735 {
736 wcf.setLocked(true);
737 }
738 else
739 {
740 wcf.setLocked(false);
741 }
742
743 if (obj instanceof Double)
744 {
745 jxl.write.Number number = new jxl.write.Number(j, i, (Double)obj, wcf);
746 sheet.addCell(number);
747
748 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
749 if (widthTemp > widthConfig[j])
750 {
751 widthConfig[j] = widthTemp;
752 }
753 }
754 else if (obj instanceof Integer)
755 {
756 jxl.write.Number number = new jxl.write.Number(j, i, (Integer)obj, wcf);
757 sheet.addCell(number);
758
759 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
760 if (widthTemp > widthConfig[j])
761 {
762 widthConfig[j] = widthTemp;
763 }
764 }
765 else if (obj instanceof Long)
766 {
767 jxl.write.Number number = new jxl.write.Number(j, i, (Long)obj, wcf);
768 sheet.addCell(number);
769
770 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
771 if (widthTemp > widthConfig[j])
772 {
773 widthConfig[j] = widthTemp;
774 }
775 }
776 else
777 {
778 Label label = new Label(j, i, (String)obj, wcf);
779 sheet.addCell(label);
780
781 widthTemp = String.valueOf(obj).getBytes("GBK").length + 1;
782 if (widthTemp > widthConfig[j])
783 {
784 widthConfig[j] = widthTemp;
785 }
786 }
787 }
788 }
789 }
790
791 if (GeneralUtils.isNotNull(param) && "suppProdSell".equals(param))
792 {
793 WritableFont font1 = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD);
794 WritableCellFormat wcf1 = new WritableCellFormat(font1);
795 wcf1.setAlignment(jxl.format.Alignment.RIGHT);
796
797 String obj = "总计(元):" + String.valueOf(totalMoney) + "元";
798 Label label = new Label(0, xlContents.size(), (String)obj, wcf1);
799 sheet.mergeCells(0, xlContents.size(), cellConfig.length - 1, xlContents.size());
800 sheet.addCell(label);
801 }
802 for (int i = 0; i < widthConfig.length; i++)
803 {
804 sheet.setColumnView(i, widthConfig[i]);
805 //System.out.println(widthConfig[i]);
806 }
807
808 book.write();
809 book.close();
810 }
811 catch (Exception e)
812 {
813 e.printStackTrace();
814 }
815
816 }
817
818 /**
819 * 讲字符串转换成byte数组
820 * @param str 字符串
821 * @return 转换后的byte数组
822 */
823 public static byte[] stringToBytes(String str)
824 {
825 try
826 {
827 if (GeneralUtils.isNotNull(str))
828 {
829 return str.getBytes(GeneralConstant.CHARACTER_CODING);
830 }
831 else
832 {
833 return new byte[0];
834 }
835
836 }
837 catch (UnsupportedEncodingException e)
838 {
839 // 该异常不会发生
840
841 return new byte[0];
842 }
843 }
844
845 /**
846 * 讲byte[]转换成字符窜
847 * @param arr byte数组
848 * @return 转换后的字符串
849 */
850 public static String bytesToSting(byte[] arr)
851 {
852 try
853 {
854 return new String(arr, GeneralConstant.CHARACTER_CODING);
855 }
856 catch (UnsupportedEncodingException e)
857 {
858 // 该异常不会发生
859
860 return "";
861 }
862 }
863
864 /**
865 * 大字段转字符串
866 *
867 * @param clob 大字段对象
868 * @return 字符串
869 * @throws Exception 异常
870 */
871 public static String clobToString(java.sql.Clob clob)
872 throws Exception
873 {
874 if (isNull(clob))
875 {
876 return " ";
877 }
878 StringBuffer sb2 = new StringBuffer();
879 Reader instream = null;
880 instream = clob.getCharacterStream();
881 BufferedReader in = new BufferedReader(instream);
882 String line = null;
883 while ((line = in.readLine()) != null)
884 {
885 sb2.append(line);
886 }
887 return sb2.toString();
888 }
889
890 /**
891 * 数量格式化工具
892 * 如果是1.0则格式化为1
893 * 如果是1.10则格式化为1.1
894 * @param number 数字
895 * @return 数字字符串
896 * @see [类、类#方法、类#成员]
897 */
898 public static String doubleToIntString(double number)
899 {
900 String numStr = String.valueOf(number);
901 if (numStr.endsWith(".0"))
902 {
903 numStr = numStr.substring(0, numStr.indexOf(".0"));
904 }
905 return numStr;
906 }
907
908 /**
909 * 格式化GOOGLE地图返回的经纬度串
910 * 源字符串格式为"(111.9009,98.47498)"
911 * 转换过后格式为"111.9009,98.47498"
912 * @param latlng
913 * @return
914 * @see [类、类#方法、类#成员]
915 */
916 public static String formatGoogleLatlng(String latlng)
917 {
918 if (GeneralUtils.isNotNullOrZeroLenght(latlng))
919 {
920 return latlng.replace("(", "").replace(")", "");
921 }
922 return null;
923 }
924
925 public static String numberFormat(Double d)
926 {
927 if (null != d)
928 {
929 DecimalFormat df = new DecimalFormat();
930 String style = "#,##0.00#";
931 df.applyPattern(style);
932 return df.format(d);
933 }
934 else
935 {
936 return null;
937 }
938 }
939
940 /**
941 * 获取当前日期的前一天的时间,如:20120410235959
942 *
943 * @return
944 * @throws Exception
945 */
946 public static String createLastDayfStr()
947 throws Exception
948 {
949 StringBuilder sb = new StringBuilder();
950
951 Calendar rightNow = Calendar.getInstance();
952
953 rightNow.add(Calendar.DATE, -1);
954
955 sb.append(rightNow.get(Calendar.YEAR));
956
957 int currentMonth = rightNow.get(Calendar.MONTH) + 1;
958
959 if (currentMonth < 10)
960 {
961 sb.append("0");
962 }
963
964 sb.append(currentMonth);
965
966 int date = rightNow.get(Calendar.DATE);
967
968 if (date < 10)
969 {
970 sb.append("0");
971 }
972
973 sb.append(date);
974
975 sb.append("235959");
976
977 return sb.toString();
978 }
979
980 /**
981 * 计算时间差 time2-time1
982 * @param unit 返回的日期格式 <br/>
983 * d:天 h:天-小时 m:天-小时-分 s:天-小时-分-秒<br/>
984 * H:小时-分-秒 M:分-秒 Hm:小时-分
985 * @param time1 时间1 格式务必为(yyyyyMMddHHmmss )(被减数)
986 * @param time2 时间2 格式务必为(yyyyMMddHHmmss )(减数)
987 * @return 时间差
988 * @throws Exception 异常
989 * @see [类、类#方法、类#成员]
990 */
991 public static String calcTimeDiff(String unit, String time1, String time2)
992 throws Exception
993 {
994 //时间单位(如:不足1天(24小时) 则返回0),开始时间,结束时间
995 Date date1 = new SimpleDateFormat("yyyyMMddHHmmss").parse(time1);
996 Date date2 = new SimpleDateFormat("yyyyMMddHHmmss").parse(time2);
997 long ltime = date1.getTime() - date2.getTime() < 0 ? date2.getTime() - date1.getTime()
998 : date1.getTime() - date2.getTime();
999 //返回天数
1000 long dnum = ltime / 86400000;
1001 //返回秒
1002 long secnum = ltime / 1000;
1003 long hnum = 0;
1004 long mnum = 0;
1005 long snum = 0;
1006 if (secnum < 86400)
1007 dnum = 0;
1008 long sd = dnum * 24 * 3600;
1009 long sh = secnum - sd;
1010 hnum = sh / 3600;
1011 long sm = sh - hnum * 3600;
1012 mnum = sm / 60;
1013 snum = sm - mnum * 60;
1014 if (unit.equals("d"))
1015 {
1016 return dnum + "天";
1017 }
1018 else if (unit.equals("h"))
1019 {
1020 return dnum + "天" + hnum + "小时";
1021 }
1022 else if (unit.equals("m"))
1023 {
1024 return dnum + "天" + hnum + "小时" + mnum + "分";
1025 }
1026 else if (unit.equals("s"))
1027 {
1028 return dnum + "天" + hnum + "小时" + mnum + "分" + snum + "秒";
1029 }
1030 else if (unit.equals("H"))
1031 {
1032 return dnum * 24 + hnum + "小时" + mnum + "分" + snum + "秒";
1033 }
1034 else if (unit.equals("M"))
1035 {
1036 return (dnum * 24 + hnum) * 60 + "分" + snum + "秒";
1037 }
1038 else if (unit.equals("Hm"))
1039 {
1040 return dnum * 24 + hnum + "小时" + mnum + "分";
1041 }
1042 else
1043 {
1044 return dnum + "天" + hnum + "小时" + mnum + "分" + snum + "秒";
1045 }
1046 }
1047
1048 /**
1049 * 获取当前时间的上一个月同等时间
1050 *
1051 * @return String 时间格式:YYYYMMDDHHMMSS
1052 * @throws Exception Exception
1053 */
1054 public static String createLastMonthTime()
1055 throws Exception
1056 {
1057 Calendar calendar = Calendar.getInstance();
1058
1059 long timeMillis = calendar.getTimeInMillis() - 2592000000l;
1060
1061 calendar.setTimeInMillis(timeMillis);
1062
1063 return GeneralUtils.date2String(calendar.getTime(), GeneralConstant.DATETIME_14);
1064 }
1065
1066 /**
1067 * 将时间段转化成用于显示的形式,如3600秒转化成1小时
1068 * @param time
1069 * @return
1070 */
1071 public static String time2View(Long time)
1072 {
1073 if (time >= 0 && time < 60)
1074 {
1075 return time + "秒";
1076 }
1077 else if (time >= 60 && time < 60 * 60)
1078 {
1079 return time / 60 + "分钟";
1080 }
1081 else if (time >= 60 * 60 && time < 60 * 60 * 24)
1082 {
1083 return time / (60 * 60) + "小时";
1084 }
1085 else if (time >= 60 * 60 * 24)
1086 {
1087 return time / (60 * 60 * 24) + "天";
1088 }
1089 else
1090 {
1091 return "";
1092 }
1093 }
1094
1095 /**
1096 * 提供精确的减法运算。
1097 * @param v1 被减数
1098 * @param v2 减数
1099 * @return 两个参数的差
1100 */
1101 public static double sub(double v1, double v2)
1102 {
1103 BigDecimal b1 = new BigDecimal(Double.toString(v1));
1104 BigDecimal b2 = new BigDecimal(Double.toString(v2));
1105 return b1.subtract(b2).doubleValue();
1106 }
1107
1108 /**
1109 * 提供精确的加法运算。
1110 * @param v1 被加数
1111 * @param v2 加数
1112 * @return 两个参数的和
1113 */
1114 public static double add(double v1, double v2)
1115 {
1116 BigDecimal b1 = new BigDecimal(Double.toString(v1));
1117 BigDecimal b2 = new BigDecimal(Double.toString(v2));
1118 return b1.add(b2).doubleValue();
1119 }
1120
1121 /**
1122 * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
1123 *
1124 * @param v1
1125 * 被除数
1126 * @param v2
1127 * 除数
1128 * @return 两个参数的商
1129 */
1130
1131 public static double div(double v1, double v2)
1132 {
1133 return div(v1, v2, 10);
1134 }
1135
1136 /**
1137 * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
1138 *
1139 * @param v1
1140 * 被除数
1141 * @param v2
1142 * 除数
1143 * @param scale
1144 * 表示表示需要精确到小数点以后几位。
1145 * @return 两个参数的商
1146 */
1147
1148 public static double div(double v1, double v2, int scale)
1149 {
1150 if (scale < 0)
1151 {
1152 throw new IllegalArgumentException("The scale must be a positive integer or zero");
1153 }
1154 BigDecimal b1 = new BigDecimal(Double.toString(v1));
1155 BigDecimal b2 = new BigDecimal(Double.toString(v2));
1156 return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
1157 }
1158
1159 public static String getParamValueByKey(Map<String, Object> paramMap, String key)
1160 {
1161 String paramValue = null;
1162 try
1163 {
1164 Object paramObject = paramMap.get(key);
1165 paramValue = paramObject.toString();
1166 }
1167 catch (Exception e)
1168 {
1169 }
1170 return paramValue;
1171 }
1172
1173 /**
1174 * 数字不足位数左补0
1175 * @param str
1176 * @param strLength
1177 * @return
1178 */
1179 public static String addZeroForNum(String str, int strLength)
1180 {
1181 return addZeroForNum(str, strLength, true);
1182 }
1183
1184 /**
1185 * 数字不足位数补0
1186 * @param str
1187 * @param strLength
1188 * @param isLeft 为true时,左补;否则,右补
1189 * @return
1190 */
1191 public static String addZeroForNum(String str, int strLength, Boolean isLeft)
1192 {
1193 int strLen = str.length();
1194 if (strLen < strLength)
1195 {
1196 while (strLen < strLength)
1197 {
1198 StringBuffer sb = new StringBuffer();
1199 str = isLeft ? sb.append("0").append(str).toString() : sb.append(str).append("0").toString();
1200 strLen = str.length();
1201 }
1202 }
1203 return str;
1204 }
1205
1206 // 将 s 进行 BASE64 编码
1207 public static String getBASE64(String s)
1208 {
1209 if (s == null)
1210 return null;
1211 return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
1212 }
1213
1214 // 将 BASE64 编码的字符串 s 进行解码
1215 public static String getFromBASE64(String s)
1216 {
1217 if (s == null)
1218 return null;
1219 BASE64Decoder decoder = new BASE64Decoder();
1220 try
1221 {
1222 byte[] b = decoder.decodeBuffer(s);
1223 return new String(b);
1224 }
1225 catch (Exception e)
1226 {
1227 return null;
1228 }
1229 }
1230
1231 //方法名称:isSameWeek(String date1,String date2)
1232 //功能描述:判断date1和date2是否在同一周
1233 //输入参数:date1,date2
1234 //输出参数:
1235 //返 回 值:false 或 true
1236 //其它说明:主要用到Calendar类中的一些方法
1237 //-----------------------------
1238 public static boolean isSameWeekOld(String date1, String date2)
1239 {
1240 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
1241 Date d1 = null;
1242 Date d2 = null;
1243 try
1244 {
1245 d1 = format.parse(date1);
1246 d2 = format.parse(date2);
1247 }
1248 catch (Exception e)
1249 {
1250 e.printStackTrace();
1251 }
1252 Calendar cal1 = Calendar.getInstance();
1253 Calendar cal2 = Calendar.getInstance();
1254 cal1.setTime(d1);
1255 cal2.setTime(d2);
1256 int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
1257 //subYear==0,说明是同一年
1258 if (subYear == 0)
1259 {
1260 if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
1261 return true;
1262 }
1263 //例子:cal1是"2005-1-1",cal2是"2004-12-25"
1264 //java对"2004-12-25"处理成第52周
1265 // "2004-12-26"它处理成了第1周,和"2005-1-1"相同了
1266 //大家可以查一下自己的日历
1267 //处理的比较好
1268 //说明:java的一月用"0"标识,那么12月用"11"
1269 else if (subYear == 1 && cal2.get(Calendar.MONTH) == 11)
1270 {
1271 if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
1272 return true;
1273 }
1274 //例子:cal1是"2004-12-31",cal2是"2005-1-1"
1275 else if (subYear == -1 && cal1.get(Calendar.MONTH) == 11)
1276 {
1277 if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
1278 return true;
1279
1280 }
1281 return false;
1282 }
1283
1284 /**
1285 * 判断两个时间是否在同一周
1286 *
1287 * @param firstDate
1288 * @param secondDate
1289 * @return
1290 * @throws ParseException
1291 */
1292 public static boolean isSameWeek(String dateStr1, String dateStr2, String format)
1293 {
1294 if (isNullOrZeroLenght(format))
1295 {
1296 format = GeneralConstant.DATETIME_14;
1297 }
1298 Date firstDate = string2Date(dateStr1, format);
1299 Date secondDate = string2Date(dateStr2, format);
1300
1301 /** 以下先根据第一个时间找出所在周的星期一、星期日, 再对第二个时间进行比较 */
1302 Calendar calendarMonday = Calendar.getInstance();
1303 calendarMonday.setTime(firstDate);
1304
1305 // 获取firstDate在当前周的第几天. (星期一~星期日:1~7)
1306 int monday = calendarMonday.get(Calendar.DAY_OF_WEEK);
1307 if (monday == 0)
1308 {
1309 monday = 7;
1310 }
1311
1312 // 星期一开始时间
1313 calendarMonday.add(Calendar.DAY_OF_MONTH, -monday + 1);
1314 calendarMonday.set(Calendar.HOUR, 0);
1315 calendarMonday.set(Calendar.MINUTE, 0);
1316 calendarMonday.set(Calendar.SECOND, 0);
1317
1318 // 星期日结束时间
1319 Calendar calendarSunday = Calendar.getInstance();
1320 calendarSunday.setTime(calendarMonday.getTime());
1321 calendarSunday.add(Calendar.DAY_OF_MONTH, 6);
1322 calendarSunday.set(Calendar.HOUR, 23);
1323 calendarSunday.set(Calendar.MINUTE, 59);
1324 calendarSunday.set(Calendar.SECOND, 59);
1325
1326 // System.out.println("星期一开始时间:" + datetimeDf.format(calendarMonday.getTime()));
1327 // System.out.println("星期日结束时间:" + datetimeDf.format(calendarSunday.getTime()));
1328
1329 // 比较第二个时间是否与第一个时间在同一周
1330 if (secondDate.getTime() >= calendarMonday.getTimeInMillis()
1331 && secondDate.getTime() <= calendarSunday.getTimeInMillis())
1332 {
1333 return true;
1334 }
1335 return false;
1336 }
1337
1338 /**
1339 * 判断两个时间是否在同一天
1340 *
1341 * 时间格式为:yyyyMMddHHmmss
1342 *
1343 * @throws ParseException
1344 */
1345 public static boolean isSameDay(String dateStr1, String dateStr2)
1346 {
1347 // 比较第二个时间是否与第一个时间在同一天
1348 if (GeneralUtils.isNotNullOrZeroLenght(dateStr1) && GeneralUtils.isNotNullOrZeroLenght(dateStr2)
1349 && dateStr1.substring(0, 8).equals(dateStr2.substring(0, 8)))
1350 {
1351 return true;
1352 }
1353 return false;
1354 }
1355
1356 /**
1357 * 判断两个时间是否在同一月
1358 *
1359 * 时间格式为:yyyyMMddHHmmss
1360 *
1361 * @throws ParseException
1362 */
1363 public static boolean isSameMonth(String dateStr1, String dateStr2)
1364 {
1365 // 比较第二个时间是否与第一个时间在同一天
1366 if (GeneralUtils.isNotNullOrZeroLenght(dateStr1) && GeneralUtils.isNotNullOrZeroLenght(dateStr2)
1367 && dateStr1.substring(0, 6).equals(dateStr2.substring(0, 6)))
1368 {
1369 return true;
1370 }
1371 return false;
1372 }
1373
1374 /**
1375 * 获取时间差,单位分钟
1376 *
1377 * 时间格式为:yyyyMMddHHmmss
1378 *
1379 * @throws ParseException
1380 */
1381 public static long getTimeDifference(String dateStr1, String dateStr2)
1382 {
1383 long min = 60;
1384 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
1385 java.util.Date now = null;
1386 java.util.Date date = null;
1387 try
1388 {
1389 now = df.parse(dateStr1);
1390 date = df.parse(dateStr2);
1391 long l = now.getTime() - date.getTime();
1392 long day = l / (24 * 60 * 60 * 1000);
1393 long hour = (l / (60 * 60 * 1000) - day * 24);
1394 min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
1395 long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
1396 min = day * 24 * 60 + hour * 60 + min;
1397 // System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
1398 }
1399 catch (ParseException e)
1400 {
1401 e.printStackTrace();
1402 }
1403 // System.out.println("min:" + min);
1404 return min;
1405 }
1406
1407 /**
1408 * 获取时间差,单位秒
1409 *
1410 * 时间格式为:yyyyMMddHHmmss
1411 *
1412 * @throws ParseException
1413 */
1414 public static long getSTimeDifference(String dateStr1, String dateStr2)
1415 {
1416 long s = 60;
1417 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
1418 java.util.Date now = null;
1419 java.util.Date date = null;
1420 try
1421 {
1422 now = df.parse(dateStr1);
1423 date = df.parse(dateStr2);
1424 long l = now.getTime() - date.getTime();
1425 long day = l / (24 * 60 * 60 * 1000);
1426 long hour = (l / (60 * 60 * 1000) - day * 24);
1427 long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
1428 s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
1429 // min = day * 24 * 60 + hour * 60 + min;
1430 s = day * 24 * 60 * 60 + hour * 60 * 60 + min * 60 + s;
1431 // System.out.println("" + day + "天" + hour + "小时" + min + "分" + s + "秒");
1432 }
1433 catch (ParseException e)
1434 {
1435 e.printStackTrace();
1436 }
1437 // System.out.println("min:" + min);
1438 return s;
1439 }
1440
1441 /**
1442 * 获取时间差,单位天
1443 *
1444 * 时间格式为:yyyyMMddHHmmss
1445 *
1446 * @throws ParseException
1447 */
1448 public static long getDayDifference(String dateStr1, String dateStr2)
1449 {
1450 long min = 60;
1451 long day = 0;
1452 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
1453 java.util.Date now = null;
1454 java.util.Date date = null;
1455 try
1456 {
1457 now = df.parse(dateStr1);
1458 date = df.parse(dateStr2);
1459 long l = now.getTime() - date.getTime();
1460 day = l / (24 * 60 * 60 * 1000);
1461 long hour = (l / (60 * 60 * 1000) - day * 24);
1462 min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
1463 long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
1464 min = day * 24 * 60 + hour * 60 + min;
1465 // System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
1466 }
1467 catch (ParseException e)
1468 {
1469 e.printStackTrace();
1470 }
1471 // System.out.println("min:" + min);
1472 return day;
1473 }
1474
1475 private static final DateFormat datetimeDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1476
1477 public static void main(String[] args)
1478 {
1479 // 定义两个时间
1480 // String dateStr1 = "2010-01-27 00:00:00";
1481 // String dateStr2 = "2010-01-30 23:59:59";
1482
1483 String dateStr1 = "20150528015525";
1484 String dateStr2 = "20150528001300";
1485 String sss="11";
1486 // getSTimeDifference(dateStr1, dateStr2);
1487 // getTimeDifference(dateStr1, dateStr2);
1488
1489 System.out.println(maxLength(sss, 2));
1490
1491 // 比较
1492 //System.out.println(isSameWeek(dateStr1, dateStr2, GeneralConstant.DATETIME_14) ? "两个时间在同一周" : "两个时间不在同一周");
1493
1494 //测试1
1495 // boolean a = isSameWeekOld("2005-1-1", "2005-1-3");
1496 // if (a)
1497 // {
1498 // System.out.println("2005-1-1和2005-1-3是同一周!");
1499 // }
1500 // else
1501 // {
1502 // System.out.println("2005-1-1和2005-1-3不是同一周!");
1503 // }
1504 //
1505 // //测试2
1506 // boolean b = isSameWeekOld("2005-1-1", "2004-12-25");
1507 // if (b)
1508 // {
1509 // System.out.println("2005-1-1和2004-12-25是同一周!");
1510 // }
1511 // else
1512 // {
1513 // System.out.println("2005-1-1和2004-12-25不是同一周!");
1514 // }
1515 //
1516 // boolean c = isSameWeekOld("2004-12-25", "2005-1-1");
1517 // if (c)
1518 // {
1519 // System.out.println("2004-12-25和2005-1-1是同一周!");
1520 // }
1521 // else
1522 // {
1523 // System.out.println("2004-12-25和2005-1-1不是同一周!");
1524 // }
1525 //
1526 // //测试3
1527 // boolean d = isSameWeekOld("2005-1-1", "2004-12-26");
1528 // if (d)
1529 // {
1530 // System.out.println("2005-1-1和2004-12-26是同一周!");
1531 // }
1532 // else
1533 // {
1534 // System.out.println("2005-1-1和2004-12-26不是同一周!");
1535 // }
1536 //
1537 // boolean e = isSameWeekOld("2004-12-26", "2005-1-1");
1538 // if (e)
1539 // {
1540 // System.out.println("2004-12-26和2005-1-1是同一周!");
1541 // }
1542 // else
1543 // {
1544 // System.out.println("2004-12-26和2005-1-1不是同一周!");
1545 // }
1546 //
1547 // System.out.println("*************************************");
1548 // //测试1
1549 // boolean a1 = isSameWeekOld("2015-1-1", "2015-1-3");
1550 // if (a1)
1551 // {
1552 // System.out.println("2015-1-1和2015-1-3是同一周!");
1553 // }
1554 // else
1555 // {
1556 // System.out.println("2015-1-1和2015-1-3不是同一周!");
1557 // }
1558 //
1559 // //测试2
1560 // boolean b1 = isSameWeekOld("2015-1-1", "2014-12-25");
1561 // if (b1)
1562 // {
1563 // System.out.println("2015-1-1和2014-12-25是同一周!");
1564 // }
1565 // else
1566 // {
1567 // System.out.println("2015-1-1和2014-12-25不是同一周!");
1568 // }
1569 //
1570 // boolean c1 = isSameWeekOld("2014-12-25", "2015-1-1");
1571 // if (c1)
1572 // {
1573 // System.out.println("2014-12-25和2015-1-1是同一周!");
1574 // }
1575 // else
1576 // {
1577 // System.out.println("2014-12-25和2015-1-1不是同一周!");
1578 // }
1579 //
1580 // //测试3
1581 // boolean d1 = isSameWeekOld("2015-1-1", "2014-12-26");
1582 // if (d1)
1583 // {
1584 // System.out.println("2015-1-1和2014-12-26是同一周!");
1585 // }
1586 // else
1587 // {
1588 // System.out.println("2015-1-1和2014-12-26不是同一周!");
1589 // }
1590 //
1591 // boolean e1 = isSameWeekOld("2014-12-26", "2015-1-1");
1592 // if (e1)
1593 // {
1594 // System.out.println("2014-12-26和2015-1-1是同一周!");
1595 // }
1596 // else
1597 // {
1598 // System.out.println("2014-12-26和2015-1-1不是同一周!");
1599 // }
1600
1601 }
1602
1603 }