java常见的时间工具类

1package com.app.common.util; 2import java.text.DecimalFormat; 3import java.text.ParseException; 4import java.text.SimpleDateFormat; 5import java.util.Calendar; 6import java.util.Date; 7import org.apache.commons.lang3.time.DateFormatUtils; 8 9public class DateUtils { 10 11 /** 12 * 仅显示年月日,例如 2015-08-11. 13 */ 14 public static final String DATE_FORMAT = "yyyy-MM-dd"; 15 /** 16 * 显示年月日时分秒,例如 2015-08-11 09:51:53. 17 */ 18 public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; 19 20 /** 21 * 仅显示时分秒,例如 09:51:53. 22 */ 23 public static final String TIME_FORMAT = "HH:mm:ss"; 24 25 /** 26 * 每天的毫秒数 8640000. 27 */ 28 public static final long MILLISECONDS_PER_DAY = 86400000L; 29 30 /** 31 * 每周的天数. 32 */ 33 public static final long DAYS_PER_WEEK = 7L; 34 35 /** 36 * 每小时毫秒数. 37 */ 38 public static final long MILLISECONDS_PER_HOUR = 3600000L; 39 40 /** 41 * 每分钟秒数. 42 */ 43 public static final long SECONDS_PER_MINUTE = 60L; 44 45 /** 46 * 每小时秒数. 47 */ 48 public static final long SECONDS_PER_HOUR = 3600L; 49 50 /** 51 * 每天秒数. 52 */ 53 public static final long SECONDS_PER_DAY = 86400L; 54 55 /** 56 * 每个月秒数,默认每月30天. 57 */ 58 public static final long SECONDS_PER_MONTH = 2592000L; 59 60 /** 61 * 每年秒数,默认每年365天. 62 */ 63 public static final long SECONDS_PER_YEAR = 31536000L; 64 65 /** 66 * 常用的时间格式. 67 */ 68 private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", 69 "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }; 70 71 /** 72 * 得到当前日期字符串. 73 * @return String 日期字符串,例如2015-08-11 74 * @since 1.0 75 */ 76 public static String getDate() { 77 return getDate(DateUtils.DATE_FORMAT); 78 } 79 80 /** 81 * 得到当前时间字符串. 82 * @return String 时间字符串,例如 09:51:53 83 * @since 1.0 84 */ 85 public static String getTime() { 86 return formatDate(new Date(), DateUtils.TIME_FORMAT); 87 } 88 89 /** 90 * 得到当前日期和时间字符串. 91 * @return String 日期和时间字符串,例如 2015-08-11 09:51:53 92 * @since 1.0 93 */ 94 public static String getDateTime() { 95 return formatDate(new Date(), DateUtils.DATETIME_FORMAT); 96 } 97 98 /** 99 * 获取当前时间指定格式下的字符串. 100 * @param pattern 101 * 转化后时间展示的格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等 102 * @return String 格式转换之后的时间字符串. 103 * @since 1.0 104 */ 105 public static String getDate(String pattern) { 106 return DateFormatUtils.format(new Date(), pattern); 107 } 108 109 /** 110 * 获取指定日期的字符串格式. 111 * @param date 需要格式化的时间,不能为空 112 * @param pattern 时间格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等 113 * @return String 格式转换之后的时间字符串. 114 * @since 1.0 115 */ 116 public static String getDate(Date date, String pattern) { 117 return DateFormatUtils.format(date, pattern); 118 } 119 120 /** 121 * 获取日期时间字符串,默认格式为(yyyy-MM-dd). 122 * @param date 需要转化的日期时间 123 * @param pattern 时间格式,例如"yyyy-MM-dd" "HH:mm:ss" "E"等 124 * @return String 格式转换后的时间字符串 125 * @since 1.0 126 */ 127 public static String formatDate(Date date, Object... pattern) { 128 String formatDate = null; 129 if (pattern != null && pattern.length > 0) { 130 formatDate = DateFormatUtils.format(date, pattern[0].toString()); 131 } else { 132 formatDate = DateFormatUtils.format(date, DateUtils.DATE_FORMAT); 133 } 134 return formatDate; 135 } 136 137 /** 138 * 获取当前年份字符串. 139 * @return String 当前年份字符串,例如 2015 140 * @since 1.0 141 */ 142 public static String getYear() { 143 return formatDate(new Date(), "yyyy"); 144 } 145 146 /** 147 * 获取当前月份字符串. 148 * @return String 当前月份字符串,例如 08 149 * @since 1.0 150 */ 151 public static String getMonth() { 152 return formatDate(new Date(), "MM"); 153 } 154 155 /** 156 * 获取当前天数字符串. 157 * @return String 当前天数字符串,例如 11 158 * @since 1.0 159 */ 160 public static String getDay() { 161 return formatDate(new Date(), "dd"); 162 } 163 164 /** 165 * 获取当前星期字符串. 166 * @return String 当前星期字符串,例如星期二 167 * @since 1.0 168 */ 169 public static String getWeek() { 170 return formatDate(new Date(), "E"); 171 } 172 173 /** 174 * 将日期型字符串转换为日期格式. 175 * 支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", 176 * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" 177 * @param str 178 * @return Date 179 * @since 1.0 180 */ 181 public static Date parseDate(Object str) { 182 if (str == null) { 183 return null; 184 } 185 try { 186 return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns); 187 } catch (ParseException e) { 188 return null; 189 } 190 } 191 192 /** 193 * 获取当前日期与指定日期相隔的天数. 194 * @param date 给定的日期 195 * @return long 日期间隔天数,正数表示给定日期在当前日期之前,负数表示在当前日期之后 196 * @since 1.0 197 */ 198 public static long pastDays(Date date) { 199 // 将指定日期转换为yyyy-MM-dd格式 200 date = DateUtils.parseDate(DateUtils.formatDate(date, DateUtils.DATE_FORMAT)); 201 // 当前日期转换为yyyy-MM-dd格式 202 Date currentDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT)); 203 long t=0; 204 if(date!=null&&currentDate!=null){ 205 t = (currentDate.getTime() - date.getTime()) / DateUtils.MILLISECONDS_PER_DAY; 206 } 207 return t; 208 } 209 210 /** 211 * 获取当前日期指定天数之后的日期. 212 * @param num 相隔天数 213 * @return Date 日期 214 * @since 1.0 215 */ 216 public static Date nextDay(int num) { 217 Calendar curr = Calendar.getInstance(); 218 curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num); 219 return curr.getTime(); 220 } 221 222 /** 223 * 获取当前日期指定月数之后的日期. 224 * @param num 间隔月数 225 * @return Date 日期 226 * @since 1.0 227 */ 228 public static Date nextMonth(int num) { 229 Calendar curr = Calendar.getInstance(); 230 curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + num); 231 return curr.getTime(); 232 } 233 234 /** 235 * 获取当前日期指定年数之后的日期. 236 * @param num 间隔年数 237 * @return Date 日期 238 * @since 1.0 239 */ 240 public static Date nextYear(int num) { 241 Calendar curr = Calendar.getInstance(); 242 curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + num); 243 return curr.getTime(); 244 } 245 246 /** 247 * 将 Date 日期转化为 Calendar 类型日期. 248 * @param date 给定的时间,若为null,则默认为当前时间 249 * @return Calendar Calendar对象 250 * @since 1.0 251 */ 252 public static Calendar getCalendar(Date date) { 253 Calendar calendar = Calendar.getInstance(); 254 // calendar.setFirstDayOfWeek(Calendar.SUNDAY);//每周从周日开始 255 // calendar.setMinimalDaysInFirstWeek(1); // 设置每周最少为1天 256 if (date != null) { 257 calendar.setTime(date); 258 } 259 return calendar; 260 } 261 262 /** 263 * 计算两个日期之间相差天数. 264 * @param start 计算开始日期 265 * @param end 计算结束日期 266 * @return long 相隔天数 267 * @since 1.0 268 */ 269 public static long getDaysBetween(Date start, Date end) { 270 // 将指定日期转换为yyyy-MM-dd格式 271 start = DateUtils.parseDate(DateUtils.formatDate(start, DateUtils.DATE_FORMAT)); 272 // 当前日期转换为yyyy-MM-dd格式 273 end = DateUtils.parseDate(DateUtils.formatDate(end, DateUtils.DATE_FORMAT)); 274 275 long diff=0; 276 if(start!=null&&end!=null) { 277 diff = (end.getTime() - start.getTime()) / DateUtils.MILLISECONDS_PER_DAY; 278 } 279 return diff; 280 } 281 282 /** 283 * 计算两个日期之前相隔多少周. 284 * @param start 计算开始时间 285 * @param end 计算结束时间 286 * @return long 相隔周数,向下取整 287 * @since 1.0 288 */ 289 public static long getWeeksBetween(Date start, Date end) { 290 return getDaysBetween(start, end) / DateUtils.DAYS_PER_WEEK; 291 } 292 293 /** 294 * 获取与指定日期间隔给定天数的日期. 295 * @param specifiedDay 给定的字符串格式日期,支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", 296 * "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", 297 * "yyyy/MM/dd HH:mm" 298 * @param num 间隔天数 299 * @return String 间隔指定天数之后的日期 300 * @since 1.0 301 */ 302 public static String getSpecifiedDayAfter(String specifiedDay, int num) { 303 Date specifiedDate = parseDate(specifiedDay); 304 Calendar c = Calendar.getInstance(); 305 c.setTime(specifiedDate); 306 int day = c.get(Calendar.DATE); 307 c.set(Calendar.DATE, day + num); 308 String dayAfter = formatDate(c.getTime(), DateUtils.DATE_FORMAT); 309 return dayAfter; 310 } 311 312 /** 313 * 计算两个日期之前间隔的小时数. 314 * 315 * @param date1 316 * 结束时间 317 * @param date2 318 * 开始时间 319 * @return String 相差的小时数,保留一位小数 320 * @since 1.0 321 */ 322 public static String dateMinus(Date date1, Date date2) { 323 if (date1 == null || date2 == null) { 324 return "0"; 325 } 326 Long r = date1.getTime() - date2.getTime(); 327 DecimalFormat df = new DecimalFormat("#.0"); 328 double result = r * 1.0 / DateUtils.MILLISECONDS_PER_HOUR; 329 return df.format(result); 330 } 331 332 /** 333 * 获取当前季度 . 334 * 335 * @return Integer 当前季度数 336 * @since 1.0 337 */ 338 public static Integer getCurrentSeason() { 339 Calendar calendar = Calendar.getInstance(); 340 Integer month = calendar.get(Calendar.MONTH) + 1; 341 int season = 0; 342 if (month >= 1 && month <= 3) { 343 season = 1; 344 } else if (month >= 4 && month <= 6) { 345 season = 2; 346 } else if (month >= 7 && month <= 9) { 347 season = 3; 348 } else if (month >= 10 && month <= 12) { 349 season = 4; 350 } 351 return season; 352 } 353 354 /** 355 * 将以秒为单位的时间转换为其他单位. 356 * 357 * @param seconds 358 * 秒数 359 * @return String 例如 16分钟前、2小时前、3天前、4月前、5年前等 360 * @since 1.0 361 */ 362 public static String getIntervalBySeconds(long seconds) { 363 StringBuffer buffer = new StringBuffer(); 364 if (seconds < SECONDS_PER_MINUTE) { 365 buffer.append(seconds).append("秒前"); 366 } else if (seconds < SECONDS_PER_HOUR) { 367 buffer.append(seconds / SECONDS_PER_MINUTE).append("分钟前"); 368 } else if (seconds < SECONDS_PER_DAY) { 369 buffer.append(seconds / SECONDS_PER_HOUR).append("小时前"); 370 } else if (seconds < SECONDS_PER_MONTH) { 371 buffer.append(seconds / SECONDS_PER_DAY).append("天前"); 372 } else if (seconds < SECONDS_PER_YEAR) { 373 buffer.append(seconds / SECONDS_PER_MONTH).append("月前"); 374 } else { 375 buffer.append(seconds / DateUtils.SECONDS_PER_YEAR).append("年前"); 376 } 377 return buffer.toString(); 378 } 379 380 /** 381 * 382 * getNowTimeBefore(记录时间相当于目前多久之前) 383 * 384 * @param seconds 385 * 秒 386 * @return 387 * @exception @since 388 * 1.0 389 * @author rlliu 390 */ 391 public static String getNowTimeBefore(long seconds) { 392 StringBuffer buffer = new StringBuffer(); 393 buffer.append("上传于"); 394 if (seconds < 3600) { 395 buffer.append((long) Math.floor(seconds / 60.0)).append("分钟前"); 396 } else if (seconds < 86400) { 397 buffer.append((long) Math.floor(seconds / 3600.0)).append("小时前"); 398 } else if (seconds < 604800) { 399 buffer.append((long) Math.floor(seconds / 86400.0)).append("天前"); 400 } else if (seconds < 2592000) { 401 buffer.append((long) Math.floor(seconds / 604800.0)).append("周前"); 402 } else if (seconds < 31104000) { 403 buffer.append((long) Math.floor(seconds / 2592000.0)).append("月前"); 404 } else { 405 buffer.append((long) Math.floor(seconds / 31104000.0)).append("年前"); 406 } 407 return buffer.toString(); 408 } 409 410 /** 411 * 412 * getMonthsBetween(查询两个日期相隔的月份) 413 * 414 * @param startDate 开始日期1 (格式yyyy-MM-dd) 415 * @param endDate 截止日期2 (格式yyyy-MM-dd) 416 * @return 417 */ 418 public static int getMonthsBetween(String startDate, String endDate) { 419 Calendar c1 = Calendar.getInstance(); 420 Calendar c2 = Calendar.getInstance(); 421 c1.setTime(DateUtils.parseDate(startDate)); 422 c2.setTime(DateUtils.parseDate(endDate)); 423 int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR); 424 int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH); 425 return Math.abs(year * 12 + month); 426 } 427 428 /** 429 * 430 * getDayOfWeek(获取当前日期是星期几) 431 * 432 * @param dateStr 日期 433 * @return 星期几 434 */ 435 public static String getDayOfWeek(String dateStr) { 436 String[] weekOfDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; 437 Date date = parseDate(dateStr); 438 Calendar calendar = Calendar.getInstance(); 439 calendar.setTime(date); 440 int num = calendar.get(Calendar.DAY_OF_WEEK) - 1; 441 return weekOfDays[num]; 442 } 443 444 /** 445 * sns 格式 如几秒前,几分钟前,几小时前,几天前,几个月前,几年后, ... 精细,类如某个明星几秒钟之前发表了一篇微博 446 * 447 * @param createTime 448 * @return 449 */ 450 public static String snsFormat(long createTime) { 451 long now = System.currentTimeMillis() / 1000; 452 long differ = now - createTime / 1000; 453 String dateStr = ""; 454 if (differ <= 60) { 455 dateStr = "刚刚"; 456 } else if (differ <= 3600) { 457 dateStr = (differ / 60) + "分钟前"; 458 } else if (differ <= 3600 * 24) { 459 dateStr = (differ / 3600) + "小时前"; 460 } else if (differ <= 3600 * 24 * 30) { 461 dateStr = (differ / (3600 * 24)) + "天前"; 462 } else { 463 Date date = new Date(createTime); 464 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 465 dateStr = sdf.format(date); 466 } 467 return dateStr; 468 } 469 470 /** 471 * 得到UTC时间,类型为字符串,格式为"yyyy-MM-dd HH:mm" 472 * 如果获取失败,返回null 473 * @return 474 */ 475 public static String getUTCTimeStr() { 476 StringBuffer UTCTimeBuffer = new StringBuffer(); 477 // 1、取得本地时间: 478 Calendar cal = Calendar.getInstance() ; 479 // 2、取得时间偏移量: 480 int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET); 481 // 3、取得夏令时差: 482 int dstOffset = cal.get(java.util.Calendar.DST_OFFSET); 483 // 4、从本地时间里扣除这些差量,即可以取得UTC时间: 484 cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset)); 485 int year = cal.get(Calendar.YEAR); 486 int month = cal.get(Calendar.MONTH)+1; 487 int day = cal.get(Calendar.DAY_OF_MONTH); 488 int hour = cal.get(Calendar.HOUR_OF_DAY); 489 int minute = cal.get(Calendar.MINUTE); 490 UTCTimeBuffer.append(year).append("-").append(month).append("-").append(day) ; 491 UTCTimeBuffer.append(" ").append(hour).append(":").append(minute) ; 492 try{ 493 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 494 sdf.parse(UTCTimeBuffer.toString()) ; 495 return UTCTimeBuffer.toString() ; 496 }catch(ParseException e) 497 { 498 e.printStackTrace() ; 499 } 500 return null ; 501 } 502}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )