java惯用日期操作对象

java常用日期操作对象
Java代码 java惯用日期操作对象java惯用日期操作对象java惯用日期操作对象
  1. import java.util.Calendar;
  2. import java.text.FieldPosition;
  3. import java.text.ParsePosition;
  4. import java.text.SimpleDateFormat;
  5. /**
  6. * 对日期的操作,如格式化,向前,向后推算日期
  7. *
  8. * @作者 刘明晶,华龙
  9. *
  10. * @时间 2008年11月17日
  11. *
  12. */
  13. public class DateUtil {
  14. static final SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy年MM月dd日");
  15. static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
  16. static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  17. /**
  18. * 判断指定日期、日期时间、时间是否比当前日期时间后。
  19. *
  20. * @param theTime 指定日期、日期时间、时间。
  21. * @return 更后返回true,否则返回false。
  22. */
  23. public static boolean isAfter(String theTime) {
  24. switch (theTime.length()) {
  25. case 5:
  26. return (get("HH:mm").compareTo(theTime) > 0);
  27. case 8:
  28. return (get("HH:mm:ss").compareTo(theTime) > 0);
  29. case 11:
  30. if (theTime.charAt(2) == ' ')
  31. return (get("dd HH:mm:ss").compareTo(theTime) > 0);
  32. if (theTime.charAt(5) == ' ')
  33. return (get("MM-dd HH:mm").compareTo(theTime) > 0);
  34. case 14:
  35. return (get("MM-dd HH:mm:ss").compareTo(theTime) > 0);
  36. case 17:
  37. return (get("yy-MM-dd HH:mm:ss").compareTo(theTime) > 0);
  38. case 19:
  39. return (get("yyyy-MM-dd HH:mm:ss").compareTo(theTime) > 0);
  40. }
  41. return false;
  42. }
  43. /**
  44. * 判断指定日期、日期时间、时间是否比当前日期时间前。
  45. *
  46. * @param theTime 指定日期、日期时间、时间。
  47. * @return 更前返回true,否则返回false。
  48. */
  49. public static boolean isBefore(String theTime) {
  50. switch (theTime.length()) {
  51. case 5:
  52. return (get("HH:mm").compareTo(theTime) < 0);
  53. case 8:
  54. return (get("HH:mm:ss").compareTo(theTime) < 0);
  55. case 11:
  56. if (theTime.charAt(2) == ' ')
  57. return (get("dd HH:mm:ss").compareTo(theTime) < 0);
  58. if (theTime.charAt(5) == ' ')
  59. return (get("MM-dd HH:mm").compareTo(theTime) < 0);
  60. case 14:
  61. return (get("MM-dd HH:mm:ss").compareTo(theTime) < 0);
  62. case 17:
  63. return (get("yy-MM-dd HH:mm:ss").compareTo(theTime) < 0);
  64. case 19:
  65. return (get("yyyy-MM-dd HH:mm:ss").compareTo(theTime) >= 0);
  66. }
  67. return false;
  68. }
  69. /**
  70. * 按照数据库日期预定的格式取得当前的日期字符串。
  71. *
  72. * * @return “yyyy-MM-dd”格式的当前时间字符串。
  73. */
  74. public static String getDate() {
  75. return sdf2.format(new java.util.Date());
  76. }
  77. /**
  78. * 获取当时指定毫秒数后的日期对象。
  79. *
  80. * @param seconds 指定毫秒数。
  81. * @return 当时指定毫秒数后的日期对象。
  82. */
  83. public static java.util.Date getDate(long seconds) {
  84. return new java.util.Date(new java.util.Date().getTime() + seconds* 1000);
  85. }
  86. /**
  87. * 按照数据库日期预定的格式取得当前的日期字符串。
  88. *
  89. * * @return “yyyy-MM-dd”格式的当前时间字符串。
  90. */
  91. public static String getDate(Calendar ca) {
  92. return sdf2.format(ca.getTime());
  93. }
  94. /**
  95. * 按照数据库日期预定的格式取得当前的日期字符串。
  96. *
  97. * * @return “yyyy-MM-dd”格式的当前时间字符串。
  98. */
  99. public static String getDate(java.util.Date date) {
  100. return sdf2.format(date);
  101. }
  102. /**
  103. * 按照指定的日期/时间格式返回日期/时间字符串。
  104. *
  105. * @param dateFormatString 格式字符串。
  106. * @return 格式化后的日期字符串。
  107. */
  108. public static String get(String dateFormatString) {
  109. try {
  110. return new java.text.SimpleDateFormat(dateFormatString)
  111. .format(new java.util.Date());
  112. } catch (Exception e) {
  113. }
  114. return null;
  115. }
  116. /**
  117. * 按照给定的 日期/时间 格式 生成 以java.util.Date对象给出的日期/时间 的字符串。
  118. *
  119. * @param date 指定的日期对象。
  120. * @param dateFormatString 格式字符串。
  121. * @return 格式化后的日期字符串。
  122. */
  123. public static String get(java.util.Date date, String dateFormatString) {
  124. try {
  125. return new java.text.SimpleDateFormat(dateFormatString)
  126. .format(date);
  127. } catch (Exception e) {
  128. }
  129. return null;
  130. }
  131. /**
  132. * 按照给定的 日期/时间 格式 生成 以java.util.Calendar对象给出的日期/时间 的字符串。
  133. *
  134. * @param calendar 指定的日历对象。
  135. * @param dateFormatString 格式字符串。
  136. * @return 格式化后的日期字符串。
  137. */
  138. public static String get(java.util.Calendar calendar, String dateFormatString) {
  139. try {
  140. return new java.text.SimpleDateFormat(dateFormatString).format(calendar
  141. .getTime());
  142. } catch (Exception e) {
  143. }
  144. return null;
  145. }
  146. /**
  147. * 自动分析多种格式的日期、日期时间、时间字符串对象解析为Calendar对象,最小级别是秒级。
  148. * 目前支持格式:
  149. * yyyy-MM-dd HH:mm:ss
  150. * MM-dd HH:mm:ss 默认为当年
  151. * dd HH:mm:ss 默认为当年当月
  152. * dd HH:mm 默认为当年当月 零秒
  153. * MM-dd HH:mm 默认为当年 零秒
  154. * yyyy-MM-dd 默认为零时零分零秒
  155. * MM-dd 默认为当年 零时零分零秒
  156. * HH:mm:ss 默认为当年当月当日
  157. * HH:mm 默认为当年当月当日 零秒
  158. *
  159. * yyyy/MM/dd HH:mm:ss
  160. * yy/MM/dd HH:mm:ss
  161. * MM/dd HH:mm:ss
  162. * dd HH:mm:ss
  163. *
  164. * yyyy年MM月dd日HH点mm分ss秒
  165. * yy年MM月dd日HH点mm分ss秒
  166. * MM月dd日HH点mm分ss秒
  167. * dd日HH点mm分ss秒
  168. * HH点mm分ss秒
  169. * HH点mm分
  170. * @param datetime 日期、日期时间、时间字符串。
  171. * @return 解析成功返回日历对象,失败返回null。
  172. */
  173. public static Calendar parse(String datetime) {
  174. if(datetime!=null){
  175. //当不是标准格式时,则进行格式化
  176. if (datetime.length()!=19) {
  177. datetime=formatToEnglish(datetime);
  178. }
  179. try {
  180. //创建一个日历对象
  181. Calendar rightNow = Calendar.getInstance();
  182. //设置日历翻到指定日期时间
  183. rightNow.setTime(sdf1.parse(datetime));
  184. //返回设置好的日期
  185. return rightNow;
  186. } catch (Exception e) { }
  187. }
  188. return null;
  189. }
  190. /**
  191. * 用指定的日期对象得到日期时间的字符串形式。
  192. *
  193. * @param date java.util.Date对象。
  194. * @return 日期时间的字符串形式。
  195. */
  196. public static String getDateTime(java.util.Date date) {
  197. return sdf1.format(date);
  198. }
  199. /**
  200. * 用给定的日期得到指定延迟秒数的日期时间字符串。
  201. *
  202. * @param date java.util.Date对象。
  203. * @param seconds 秒数。
  204. * @return 延迟后的日期时间。
  205. */
  206. public static String getDateTime(java.util.Date date, int seconds) {
  207. return sdf1.format(new java.util.Date(date.getTime() + seconds * 1000));
  208. }
  209. /**
  210. * 获得今日与指定日历之间的天数。
  211. *
  212. * @param last 指定的日历。
  213. * @return 当日与指定日历之间的天数。
  214. */
  215. public static int getDays(Calendar last) {
  216. Calendar right = Calendar.getInstance();
  217. long theTime = right.getTimeInMillis() - last.getTimeInMillis();
  218. return (int) (theTime / (3600000 * 24));
  219. }
  220. private static int seed = 0;
  221. /**
  222. * 获取毫秒级的指定长度的字符串。
  223. * @param length 指定的字符串长度。
  224. * @return 毫秒级的指定长度的字符串。
  225. */
  226. public static String getRandomString(int length) {
  227. seed++;
  228. Calendar right = Calendar.getInstance();
  229. String tmp = Long.toString(right.getTimeInMillis() * seed + seed);
  230. length = tmp.length() - length;
  231. return (length < 0) ? tmp : tmp.substring(length);
  232. }
  233. /**
  234. * 用指定格式的日期时间来的得到日期时间对象。
  235. *
  236. * @param dateFormatString 日期时间格式字符串。
  237. * @return 返回java.util.Date类型日期时间对象。
  238. */
  239. public static java.util.Date getToday(String dateFormatString) {
  240. try {
  241. return parse(
  242. new java.text.SimpleDateFormat(dateFormatString)
  243. .format(Calendar.getInstance().getTime()))
  244. .getTime();
  245. } catch (Exception e) {
  246. }
  247. return null;
  248. }
  249. /**
  250. * 得到指定格式的当日的后一天的日期时间对象。
  251. *
  252. * @param dateFormatString 日期时间格式字符串。
  253. * @return 返回java.util.Date类型日期时间对象。
  254. */
  255. public static java.util.Date getTomorrow(String dateFormatString) {
  256. try {
  257. return parse(
  258. new java.text.SimpleDateFormat(dateFormatString)
  259. .format(new java.util.Date(new java.util.Date()
  260. .getTime() + 24 * 3600 * 1000))).getTime();
  261. } catch (Exception e) {
  262. }
  263. return null;
  264. }
  265. /**
  266. * 返回今天之前或之后若干天的日期字符串。
  267. * @param days 指定的天数,“days<0”表示前days天;“days>0”表示后days天,“days=0”表示当天。
  268. * @return 返回格式为“yyyy-MM-dd”的日期。
  269. */
  270. public static String getDate(int days) {
  271. Calendar now = Calendar.getInstance();
  272. now.add(Calendar.DAY_OF_MONTH, days);
  273. return sdf2.format(now.getTime());
  274. }
  275. /**
  276. * 得到指定date日期之前或之后若干天的日期字符串。
  277. * @param date 指定的日期字符串。
  278. * @param days 指定的天数,“days<0”表示前days天;“days>0”表示后days天,“days=0”表示当天。
  279. * @return 字符串形式的日期。
  280. */
  281. public static String getDate(String date,int days){
  282. java.util.Date dateTemp = sdf2.parse(date, new ParsePosition(0));
  283. Calendar calendar = Calendar.getInstance();
  284. calendar.setTime(dateTemp);
  285. // 要加减的日期
  286. calendar.add(Calendar.DATE, days);
  287. java.util.Date nowTime = calendar.getTime();
  288. StringBuffer buffer = sdf2.format(nowTime, new StringBuffer(""),new FieldPosition(0));
  289. return new String(buffer);
  290. }
  291. /**
  292. * 格式化以:“年”、“月”、“日”、“时”、“分”、“秒”、“-”、“-”、“:”、“/”、“ ”、“ ”
  293. * 分割日期时间的日期时间字符串。统一格式化成英文的日期时间,例:2009-11-09 13:32:56。
  294. */
  295. public static String formatToEnglish(String datetime){
  296. String date=sdf2.format(Calendar.getInstance().getTime());
  297. String yy=date.substring(0,2);
  298. String year=date.substring(0,4);
  299. String month=date.substring(5,7);
  300. String day=date.substring(8,10);
  301. String datetimeBak=datetime.replace("日", " ");
  302. datetimeBak=datetimeBak.replace(" ", " ");
  303. datetimeBak=datetimeBak.replaceAll(" +", " ");
  304. //把日期和时间切割成两部分
  305. String dt[]=datetimeBak.split(" ");
  306. String format=null;
  307. String temp[]=getArray(datetime);
  308. if(temp!=null&&dt!=null){
  309. switch (temp.length){
  310. case 1:
  311. //只有日
  312. if(temp[0].length()==1){
  313. temp[0]="0"+temp[0];
  314. }
  315. format=year+"-"+month+"-"+temp[1]+" 00:00:00";
  316. break;
  317. case 2:
  318. for (int i = 0; i < temp.length; i++) {
  319. if(temp[i].length()==1){
  320. temp[i]="0"+temp[i];
  321. }
  322. }
  323. //判断为日期或是时间
  324. if(dt.length==1){
  325. //判断为时间:由时、分、秒组成
  326. if(dt[0].contains(":")||dt[0].contains(":")||dt[0].contains("点")){
  327. format=year+"-"+month+"-"+day+" "+temp[0]+":"+temp[1]+":00";
  328. }
  329. //判断为日期:由月、日组成
  330. else{
  331. format=year+"-"+temp[0]+"-"+temp[1]+" 00:00:00";
  332. }
  333. }
  334. //判断为日期时间:由日、时组成
  335. else if(dt.length==2){
  336. format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":00:00";
  337. }
  338. break;
  339. case 3:
  340. //判断为日期或是时间
  341. if(dt.length==1){
  342. //判断为时间:由时、分、秒组成
  343. if(dt[0].contains(":")||dt[0].contains(":")||dt[0].contains("点")){
  344. for (int i = 0; i < temp.length; i++) {
  345. if(temp[i].length()==1){
  346. temp[i]="0"+temp[i];
  347. }
  348. }
  349. format=year+"-"+month+"-"+day+" "+temp[0]+":"+temp[1]+":"+temp[2];
  350. }
  351. //判断为日期:由年、月、日组成
  352. else{
  353. for (int i = 0; i < temp.length; i++) {
  354. if(temp[0].length()!=4){
  355. temp[0]=yy+temp[0];
  356. }
  357. else if(temp[i].length()==1){
  358. temp[i]="0"+temp[i];
  359. }
  360. }
  361. format=temp[0]+"-"+temp[1]+"-"+temp[2]+" 00:00:00";
  362. }
  363. }
  364. //判断为日期时间:由日、时组成
  365. else if(dt.length==2){
  366. for (int i = 0; i < temp.length; i++) {
  367. if(temp[i].length()==1){
  368. temp[i]="0"+temp[i];
  369. }
  370. }
  371. String dateArray[]=getArray(dt[0]);
  372. String timeArray[]=getArray(dt[1]);
  373. //判断为月、日、时组成
  374. if(dateArray.length==2 && timeArray.length==1){
  375. format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":00:00";
  376. }
  377. //判断为日、时、分组成
  378. else if(dateArray.length==1 && timeArray.length==2){
  379. format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":"+temp[2]+":00";
  380. }
  381. }
  382. break;
  383. case 4:
  384. //判断为日期时间
  385. if(dt.length==2){
  386. String dateArray[]=getArray(dt[0]);
  387. String timeArray[]=getArray(dt[1]);
  388. //判断为年、月、日、时组成
  389. if(dateArray.length==3 && timeArray.length==1){
  390. for (int i = 0; i < temp.length; i++) {
  391. if(temp[0].length()!=4){
  392. temp[0]=yy+temp[0];
  393. }
  394. else if(temp[i].length()==1){
  395. temp[i]="0"+temp[i];
  396. }
  397. }
  398. format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+"00:00";
  399. }
  400. else{
  401. for (int i = 0; i < temp.length; i++) {
  402. if(temp[i].length()==1){
  403. temp[i]="0"+temp[i];
  404. }
  405. }
  406. //判断为日、时、分、秒组成
  407. if(dateArray.length==1 && timeArray.length==3){
  408. format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":"+temp[2]+":"+temp[3];
  409. }
  410. //判断为月、日、时、分组成
  411. else if(dateArray.length==2 && timeArray.length==2){
  412. format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":"+temp[3]+":00";
  413. }
  414. }
  415. }
  416. break;
  417. case 5:
  418. if(dt.length==2){
  419. String dateArray[]=getArray(dt[0]);
  420. String timeArray[]=getArray(dt[1]);
  421. //判断为月、日、时、分、秒组成
  422. if(dateArray.length==2 && timeArray.length==3){
  423. for (int i = 0; i < temp.length; i++) {
  424. if(temp[i].length()==1){
  425. temp[i]="0"+temp[i];
  426. }
  427. }
  428. format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":"+temp[3]+":"+temp[4];
  429. }
  430. //判断为年、月、日、时、分组成
  431. else if(dateArray.length==3 && timeArray.length==2){
  432. for (int i = 0; i < temp.length; i++) {
  433. if(temp[0].length()!=4){
  434. temp[0]=yy+temp[0];
  435. }
  436. else if(temp[i].length()==1){
  437. temp[i]="0"+temp[i];
  438. }
  439. }
  440. format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+temp[4]+":00";
  441. }
  442. }
  443. break;
  444. case 6:
  445. for (int i = 0; i < temp.length; i++) {
  446. if(temp[0].length()!=4){
  447. temp[0]=yy+temp[0];
  448. }
  449. else if(temp[i].length()==1){
  450. temp[i]="0"+temp[i];
  451. }
  452. }
  453. format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+temp[4]+":"+temp[5];
  454. break;
  455. }
  456. }
  457. return format;
  458. }
  459. /**
  460. * 把多种中文中易出现格式的日期时间中各项转换成数组。
  461. */
  462. private static String[] getArray(String datetime){
  463. String array[]=null;
  464. if(datetime!=null){
  465. //把半角空格替换掉
  466. datetime=datetime.replace(" ", "-");
  467. //把全角空格替换掉
  468. datetime=datetime.replace(" ", "-");
  469. datetime=datetime.replace("年", "-");
  470. datetime=datetime.replace("月", "-");
  471. datetime=datetime.replace("日", "-");
  472. datetime=datetime.replace("点", "-");
  473. datetime=datetime.replace("分", "-");
  474. datetime=datetime.replace("秒", "");
  475. datetime=datetime.replace(",", "-");
  476. datetime=datetime.replace(",", "-");
  477. datetime=datetime.replace(".", "-");
  478. datetime=datetime.replace(":", "-");
  479. datetime=datetime.replace(":", "-");
  480. datetime=datetime.replace("-", "-");
  481. datetime=datetime.replace("/", "-");
  482. //多个“-”替换成一个“-”
  483. datetime=datetime.replaceAll("-+", "-");
  484. //把日期时间分割成每个项
  485. array=datetime.split("-");
  486. }
  487. return array;
  488. }
  489. /**
  490. * 格式化以:“年”、“月”、“日”、“时”、“分”、“秒”、“-”、“-”、“:”、“/”、“ ”、“ ”
  491. * 分割日期时间的日期时间字符串。统一格式化成中文的日期时间,例:2009年11月09日13时32分56秒。
  492. */
  493. public static String formatToChinese(String datetime){
  494. datetime=formatToEnglish(datetime);
  495. if(datetime==null||datetime.equals("")){
  496. return null;
  497. }
  498. String str[]=datetime.split(":|-| ");
  499. return str[0]+"年"+str[1]+"月"+str[2]+"日 "+str[3]+"点"+str[4]+"分"+str[5]+"秒";
  500. }