DateUtil.java 11.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
package com.wondertek.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author w4178
 */
@Slf4j
public class DateUtil {

	public static final String regex = "yyyy-MM-dd HH:mm:ss";

	private static final SimpleDateFormat sdf = new SimpleDateFormat(regex);

	private static final ThreadLocal<Map<String, DateFormat>> dateFormatThreadLocal = new ThreadLocal();

	public static LocalDateTime toLocalDateTime(Date date) {
		if (date != null) {
//			return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
//			return date.toInstant().atOffset(ZoneOffset.of("+0")).toLocalDateTime();
			return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
		}
		return null;
	}

	public static Date asDate(LocalDateTime localDateTime){
		return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
	}

	public static LocalDateTime asLocalDateTime(Date date){
		return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
	}

	public static String format(LocalDateTime date) {
		try {
			if (date != null) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
				return df.format(date);
			}
		} catch (Exception e) {
			log.error("date 日期格式化错误:" + e.getMessage());
		}
		return "";
	}

	public static String format(Date date, String patten) {
		return getDateFormat(patten).format(date);
	}


	private static DateFormat getDateFormat(String pattern) {
		if (pattern != null && pattern.trim().length() != 0) {
			Map<String, DateFormat> dateFormatMap = (Map)dateFormatThreadLocal.get();
			if (dateFormatMap != null && ((Map)dateFormatMap).containsKey(pattern)) {
				return (DateFormat)((Map)dateFormatMap).get(pattern);
			} else {
				synchronized(dateFormatThreadLocal) {
					if (dateFormatMap == null) {
						dateFormatMap = new HashMap();
					}

					((Map)dateFormatMap).put(pattern, new SimpleDateFormat(pattern));
					dateFormatThreadLocal.set(dateFormatMap);
				}

				return (DateFormat)((Map)dateFormatMap).get(pattern);
			}
		} else {
			throw new IllegalArgumentException("pattern cannot be empty.");
		}
	}

	public static String dateToString(Date d,String format)
	{
		return new SimpleDateFormat(format).format(d);
	}

	public static String dateToString(Date d)
	{
		return new SimpleDateFormat(regex).format(d);
	}

	public static Date stringToDate(String s,String format) throws ParseException
	{
		return new SimpleDateFormat(format).parse(s);
	}

	public static Date stringToDate(String s) throws ParseException
	{
		return new SimpleDateFormat(regex).parse(s);
	}



	public static String resolve(LocalDateTime localDateTime) {
		try {
			if (localDateTime != null) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
				return df.format(localDateTime);
			}
		} catch (Exception e) {
			log.error("date 日期格式化错误:" + e.getMessage());
		}
		return "";
	}

	public static Long getTime(LocalDateTime localDateTime) {
		if (localDateTime != null) {
			Date date = DateUtil.toDate(localDateTime);
			return date.getTime();
		}
		return null;
	}

	public static Date toDate(LocalDateTime localDateTime) {
		if (localDateTime != null) {
			ZoneId zoneId = ZoneId.systemDefault();
			ZonedDateTime zdt = localDateTime.atZone(zoneId);
			return Date.from(zdt.toInstant());
		}
		return null;
	}

	public static Date toDate(String content) {
		if (!StringUtils.isEmpty(content) && !"null".equals(content)) {
			Long time = getTime(content);
			if (time != null) {
				return new Date(time);
			}
		}
		return null;
	}

	/**
	 * <p><b>Title:</b> listBetweenMinutes</p>
	 * <p><b>Description:</b> 得到时间范围内所有时间(按分钟算),开始时间不算</p>
	 *
	 * @param startTime
	 * @param endTime
	 * @param s         间隔多少分钟
	 * @return
	 * @author Zewei.Zhou
	 */
	public static List<LocalDateTime> listBetweenMinutes(LocalDateTime startTime, LocalDateTime endTime, int s) {
		long between = ChronoUnit.MINUTES.between(startTime.withSecond(0).withNano(0),
				endTime.withSecond(0).withNano(0));
		Assert.state(between >= 0, "开始时间必须小于等于结束时间");

		List<LocalDateTime> list = new ArrayList<>(Integer.parseInt(between + ""));

		list.add(startTime);
		for (int i = s; i < between; i = i + s) {
			list.add(startTime.plusMinutes(i));

		}

		return list;
	}

	public static boolean checkBetweenDays(String startTime,String endTime,Long days){
		try {
			long between = ChronoUnit.DAYS.between(DateUtil.str2date(startTime).withSecond(0).withNano(0),
					DateUtil.str2date(endTime).withSecond(0).withNano(0));
			return between > days;
		}catch (Exception ex){
			return false;
		}
	}

	public static Long getTimeMill(String timeStr) {
		String defaultDateFormat = "yyyy-MM-dd HH:mm:ss";
		timeStr = timeStr.trim();
		boolean flag = isDate(timeStr, defaultDateFormat);
		if (flag) {
			LocalDateTime localDateTime = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern(defaultDateFormat));
			Date date = DateUtil.toDate(localDateTime);
			return date.getTime();
		}
		return null;
	}

	/**
	 * 判断是否为合法的日期时间字符串
	 *
	 * @param dateStr 时间字符串
	 * @param rDateFormat 时间格式化模板
	 * @return boolean;符合为true,不符合为false
	 */
	public static boolean isDate(String dateStr, String rDateFormat) {
		if (!StringUtils.isEmpty(dateStr)) {
			SimpleDateFormat formatter = new SimpleDateFormat(rDateFormat);
			formatter.setLenient(false);
			try {
				formatter.format(formatter.parse(dateStr));
			} catch (Exception e) {
				return false;
			}
			return true;
		}
		return false;
	}

	/**
	 * localDateTime装换为Date
	 *
	 * @param localDateTime localDateTime
	 * @return Date
	 */
	public static Date localDateTimeToDate(LocalDateTime localDateTime) {
		if (localDateTime == null) {
			return null;
		}
		ZoneId zoneId = ZoneId.systemDefault();
		Instant instant = localDateTime.atZone(zoneId).toInstant();
		return Date.from(instant);
	}

	// 把时间转为字符串
	public static String date2Str(LocalDateTime time, String format) {
		try {
			DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
			return pattern.format(time);
		} catch (Exception e) {
			log.info("时间转换为字符串异常:" + e.getMessage());
		}
		return null;
	}

	// 把字符串转换为时间
	public static LocalDateTime str2date(String timeStr, String format) {
		try {
			DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
			return LocalDateTime.parse(timeStr, pattern);
		} catch (Exception e) {
			log.info("字符串转换为时间异常:" + e.getMessage());
		}
		return null;
	}

	// 把字符串转换为时间
	public static LocalDateTime str2date(String timeStr) {
		try {
			DateTimeFormatter pattern = DateTimeFormatter.ofPattern(regex);
			return LocalDateTime.parse(timeStr, pattern);
		} catch (Exception e) {
			log.info("字符串转换为时间异常:" + e.getMessage());
		}
		return null;
	}

	public static boolean isInTimeInterval(LocalDateTime nowTime,LocalDateTime startTime,LocalDateTime endTime){
		if (startTime ==null){
			return true;
		}
		if (endTime ==null){
			return true;
		}
		if (nowTime.isAfter(startTime) && nowTime.isBefore(endTime)){
			return true;
		}

		return false;
	}






	public static String secToTime(int time) {
		String timeStr;
		int hour;
		int minute;
		int second;
		if (time <= 0) {
			return "00:00:00";
		} else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = "00:" + unitFormat(minute) + ":" + unitFormat(second);
			} else {
				hour = minute / 60;
				if (hour > 99) {
					return "99:59:59";
				}
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
			}
		}
		return timeStr;
	}

	private static String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10) {
			retStr = "0" + Integer.toString(i);
		} else {
			retStr = "" + i;
		}
		return retStr;
	}

	public static List<String> listBetweenDays(String startTime, String endTime) {
		List<String> resultList = new ArrayList<>(16);

		DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate startDate = LocalDate.parse(startTime, pattern);
		LocalDate endDate = LocalDate.parse(endTime, pattern);
		while (startDate.isBefore(endDate) || startDate.isEqual(endDate)) {
			resultList.add(pattern.format(startDate));
			startDate = startDate.plusDays(1);
		}
		return resultList;
	}

	public static Long getTime(String content) {
		String regex = "yyyy-MM-dd HH:mm:ss";
		if (isDate(content.trim(), regex)) {
			try {
				Date d = sdf.parse(content);
				return d.getTime();
			} catch (ParseException e) {
				log.error("{},格式化异常:{}", regex, e.getMessage());
			}
		}
		return null;
	}

	public static boolean  compareStartEndTime(String startTime,String endTime){
		boolean flag =true;
		int compareTo = startTime.compareTo(endTime);
		if(compareTo>0){
			flag= false;
		}

		return flag;
	}






    public static boolean isDateVail(String date){
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(regex);
		boolean flag =true;
		try {
			LocalDateTime.parse(date, dtf);
		}catch (Exception ex){
			flag =false;
		}
       return false;
	}


	public static LocalDateTime toStartOfDay(LocalDateTime time) {
		return time.withHour(0).withMinute(0).withSecond(0).withNano(0);
	}

	public static String[] getLastMonthFirstAndLastDay(){
		LocalDateTime time = LocalDateTime.now().minusMonths(6L);
		LocalDateTime dayStart = DateUtil.getDayStart(time);
		String format = DateUtil.format(dayStart);
		return new String[]{"",format};
	}



	public static String[] getLastMonthFirstAndLastDays(){
		SimpleDateFormat sm = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		//上个月
		cal.add(Calendar.MONTH, -3);
		cal.set(Calendar.DAY_OF_MONTH,1);
		String firstDay = sm.format(cal.getTime());
		Calendar call = Calendar.getInstance();
		//设置上个月最后一天
		call.add(Calendar.MONTH, -2);
		call.set(Calendar.DAY_OF_MONTH,0);
		String lastDay = sm.format(call.getTime());
		return new String[]{firstDay,lastDay};
	}



	private static LocalDateTime getDate(String beforeDate) throws Exception{

		SimpleDateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		Date rdate = readFormat.parse(beforeDate);

		SimpleDateFormat writeFormat = new SimpleDateFormat(regex, Locale.US);
		String format = writeFormat.format(rdate);
	return 	asLocalDateTime(writeFormat.parse(format));



	}



	// 获取一天的开始时间,2017,7,22 00:00
	public static LocalDateTime getDayStart(LocalDateTime time) {
		return time.withHour(0).withMinute(0).withSecond(0).withNano(0);
	}

	// 获取一天的结束时间,2017,7,22 23:59:59.999999999
	public static LocalDateTime getDayEnd(LocalDateTime time) {
		return time.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
	}



}