DateUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /**
  2. * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.cslg.ids.common.utils;
  17. import org.apache.commons.lang3.StringUtils;
  18. import org.apache.commons.lang3.time.DateFormatUtils;
  19. import java.sql.Timestamp;
  20. import java.text.DateFormat;
  21. import java.text.ParseException;
  22. import java.text.SimpleDateFormat;
  23. import java.time.*;
  24. import java.time.format.DateTimeFormatter;
  25. import java.time.temporal.ChronoUnit;
  26. import java.time.temporal.TemporalAdjusters;
  27. import java.util.Calendar;
  28. import java.util.Date;
  29. import java.util.HashMap;
  30. import java.util.Map;
  31. import java.util.concurrent.TimeUnit;
  32. public class DateUtil {
  33. /**
  34. * 获取YYYY格式
  35. *
  36. * @return
  37. */
  38. public static String getYear() {
  39. return formatDate(new Date(), "yyyy");
  40. }
  41. /**
  42. * 获取YYYY格式
  43. *
  44. * @return
  45. */
  46. public static String getYear(Date date) {
  47. return formatDate(date, "yyyy");
  48. }
  49. public static String getCurrentServerDate(String format) {
  50. return formatDate(new Date(), format);
  51. }
  52. /**
  53. * 获取YYYY-MM-DD格式
  54. *
  55. * @return
  56. */
  57. public static String getDay() {
  58. return formatDate(new Date(), "yyyy-MM-dd");
  59. }
  60. /**
  61. * 获取YYYY-MM-DD格式
  62. *
  63. * @return
  64. */
  65. public static String getDay(Date date) {
  66. return formatDate(date, "yyyy-MM-dd");
  67. }
  68. /**
  69. * 获取YYYYMMDD格式
  70. *
  71. * @return
  72. */
  73. public static String getDays() {
  74. return formatDate(new Date(), "yyyyMMdd");
  75. }
  76. /**
  77. * 获取YYYYMMDD格式
  78. *
  79. * @return
  80. */
  81. public static String getDays(Date date) {
  82. return formatDate(date, "yyyyMMdd");
  83. }
  84. /**
  85. * 获取YYYY-MM-DD HH:mm:ss格式
  86. *
  87. * @return
  88. */
  89. public static String getTime() {
  90. return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
  91. }
  92. /**
  93. * 获取YYYY-MM-DD HH:mm:ss.SSS格式
  94. *
  95. * @return
  96. */
  97. public static String getMsTime() {
  98. return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
  99. }
  100. /**
  101. * 获取YYYYMMDDHHmmss格式
  102. *
  103. * @return
  104. */
  105. public static String getAllTime() {
  106. return formatDate(new Date(), "yyyyMMddHHmmss");
  107. }
  108. /**
  109. * 获取YYYY-MM-DD HH:mm:ss格式
  110. *
  111. * @return
  112. */
  113. public static String getTime(Date date) {
  114. return formatDate(date, "yyyy-MM-dd HH:mm:ss");
  115. }
  116. public static String formatDate(Date date, String pattern) {
  117. String formatDate = null;
  118. if (StringUtils.isNotBlank(pattern)) {
  119. formatDate = DateFormatUtils.format(date, pattern);
  120. } else {
  121. formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
  122. }
  123. return formatDate;
  124. }
  125. /**
  126. * 格式化日期
  127. *
  128. * @return
  129. */
  130. public static String format(Date date, String pattern) {
  131. return DateFormatUtils.format(date, pattern);
  132. }
  133. /**
  134. * 把日期转换为Timestamp
  135. *
  136. * @param date
  137. * @return
  138. */
  139. public static Timestamp format(Date date) {
  140. return new Timestamp(date.getTime());
  141. }
  142. public static int getDiffYear(String startTime, String endTime) {
  143. DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  144. try {
  145. int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(
  146. startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
  147. return years;
  148. } catch (Exception e) {
  149. // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
  150. return 0;
  151. }
  152. }
  153. /**
  154. * <li>功能描述:时间相减得到天数
  155. *
  156. * @param beginDateStr
  157. * @param endDateStr
  158. * @return long
  159. * @author Administrator
  160. */
  161. public static long getDaySub(String beginDateStr, String endDateStr) {
  162. long day = 0;
  163. SimpleDateFormat format = new SimpleDateFormat(
  164. "yyyy-MM-dd");
  165. Date beginDate = null;
  166. Date endDate = null;
  167. try {
  168. beginDate = format.parse(beginDateStr);
  169. endDate = format.parse(endDateStr);
  170. } catch (ParseException e) {
  171. e.printStackTrace();
  172. }
  173. day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
  174. // System.out.println("相隔的天数="+day);
  175. return day;
  176. }
  177. /**
  178. * 得到n天之后的日期
  179. *
  180. * @param days
  181. * @return
  182. */
  183. public static String getAfterDayDate(String days) {
  184. int daysInt = Integer.parseInt(days);
  185. Calendar canlendar = Calendar.getInstance(); // java.util包
  186. canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
  187. Date date = canlendar.getTime();
  188. SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  189. String dateStr = sdfd.format(date);
  190. return dateStr;
  191. }
  192. /**
  193. * 得到n天之后是周几
  194. *
  195. * @param days
  196. * @return
  197. */
  198. public static String getAfterDayWeek(String days) {
  199. int daysInt = Integer.parseInt(days);
  200. Calendar canlendar = Calendar.getInstance(); // java.util包
  201. canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
  202. Date date = canlendar.getTime();
  203. SimpleDateFormat sdf = new SimpleDateFormat("E");
  204. String dateStr = sdf.format(date);
  205. return dateStr;
  206. }
  207. /**
  208. * 格式化Oracle Date
  209. * @param value
  210. * @return
  211. */
  212. // public static String buildDateValue(Object value){
  213. // if(Func.isOracle()){
  214. // return "to_date('"+ value +"','yyyy-mm-dd HH24:MI:SS')";
  215. // }else{
  216. // return Func.toStr(value);
  217. // }
  218. // }
  219. /**
  220. * @Description: 获取当前时间的周一及周日
  221. * @Param: Date
  222. * @Author: LHX
  223. * @Date: 9:59 2018/11/19
  224. * @return: java.util.Map<java.lang.String,java.lang.String>
  225. */
  226. public static Map<String,String> getWeekDate(Date date) {
  227. Map<String,String> map = new HashMap();
  228. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  229. Calendar cal = Calendar.getInstance();
  230. cal.setTime(date);
  231. // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
  232. cal.setFirstDayOfWeek(Calendar.MONDAY);
  233. // 获得当前日期是一个星期的第几天
  234. int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
  235. if(dayWeek==1){
  236. dayWeek = 8;
  237. }
  238. // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
  239. cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
  240. Date mondayDate = cal.getTime();
  241. String weekBegin = sdf.format(mondayDate);
  242. //获取星期日
  243. cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
  244. Date sundayDate = cal.getTime();
  245. String weekEnd = sdf.format(sundayDate);
  246. map.put("mondayDate", weekBegin);
  247. map.put("sundayDate", weekEnd);
  248. return map;
  249. }
  250. public static void main(String[] args) {
  251. System.out.println(getTime(new Date()));
  252. System.out.println(getAfterDayWeek("3"));
  253. }
  254. public static Long getRemainingSecond() {
  255. // 获取当前时间
  256. LocalDateTime now = LocalDateTime.now();
  257. // 计算当天零点的时间
  258. LocalDateTime midnight = now.plusDays(1).truncatedTo(ChronoUnit.DAYS);
  259. // 转换为ZonedDateTime以获取时区信息
  260. ZonedDateTime zonedDateTime = midnight.atZone(ZoneId.systemDefault());
  261. // 转换为Unix时间戳(秒)
  262. long midnightTimestamp = TimeUnit.MILLISECONDS.toSeconds(zonedDateTime.toInstant().toEpochMilli());
  263. // 获取当前时间的Unix时间戳(秒)
  264. long currentTimestamp = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
  265. // 计算剩余秒数直到当天零点
  266. // // 如果已经过了零点,则设置过期时间为0或者重新计算逻辑
  267. // if (ttlSeconds <= 0) {
  268. // ttlSeconds = 0; // 或者你可以设置为其他逻辑,比如下一个天的零点
  269. // }
  270. return midnightTimestamp - currentTimestamp;
  271. }
  272. /**
  273. * 获取当前日期减1天的 Date 对象
  274. */
  275. public static Date getYesterdayDate() {
  276. // 使用 Java 8 的 LocalDate 计算日期
  277. LocalDate yesterdayLocalDate = LocalDate.now().minusDays(1);
  278. // 将 LocalDate 转换为 Date 对象(基于系统默认时区)
  279. return Date.from(yesterdayLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
  280. }
  281. /**
  282. * 获取当前日期减1天的 String 对象
  283. */
  284. public static String getYesterdayDateStr() {
  285. return LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
  286. }
  287. /**
  288. * 获取当前日期的 String 对象
  289. */
  290. public static String getNowStr() {
  291. return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月"));
  292. }
  293. /**
  294. * 获取当前日期减1月的 String 对象
  295. */
  296. public static String getNowYearStr() {
  297. return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年"));
  298. }
  299. /**
  300. * 获取当前日期减1月的 String 对象
  301. */
  302. public static String getNowMonthStr() {
  303. return LocalDate.now().format(DateTimeFormatter.ofPattern("MM"));
  304. }
  305. /**
  306. * 获取当前日期减1月的 String 对象
  307. */
  308. public static String getLastYearStr() {
  309. return LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy年"));
  310. }
  311. /**
  312. * 获取当前日期减1月的 String 对象
  313. */
  314. public static String getLastMonthStr() {
  315. return LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("MM"));
  316. }
  317. /**
  318. * 获取当前日期 String 对象
  319. */
  320. public static String getNowDateStr() {
  321. return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
  322. }
  323. /**
  324. * 获取当前日期的上月第一天 String 对象
  325. */
  326. public static String getFirstDayOfMonthStr() {
  327. return LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
  328. }
  329. /**
  330. * 获取当前日期的上月最后一天 String 对象
  331. */
  332. public static String getLastDayOfMonthStr() {
  333. return LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
  334. }
  335. /**
  336. * 判断两个 Date 对象的日期部分是否相等(忽略时间)
  337. */
  338. public static boolean isDateEqualIgnoreTime(Date date1, Date date2) {
  339. if (date1 == null || date2 == null) {
  340. return false;
  341. }
  342. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  343. String str1 = sdf.format(date1);
  344. String str2 = sdf.format(date2);
  345. return str1.equals(str2);
  346. }
  347. public static String convertTimestamp(long timestamp) {
  348. // 将秒级时间戳转换为Instant对象
  349. Instant instant = Instant.ofEpochSecond(timestamp);
  350. // 创建日期格式化器,并指定UTC时区
  351. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
  352. .withZone(ZoneId.of("GMT+8"));
  353. // 格式化Instant为字符串
  354. return formatter.format(instant);
  355. }
  356. }