package com.cnksi.utils;
import com.cnksi.app.model.WechatWorkDate;
import org.apache.commons.lang.time.DateUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateUtil {
private DateUtil() {
}
public static Date subDate(Date date, int minutes) {
long times = date.getTime();
times = times - minutes * 60 * 1000;
return new Date(times);
}
/**
* yyyy-MM-dd
*/
static SimpleDateFormat sdfYmd = new SimpleDateFormat("yyyy-MM-dd");
public static SimpleDateFormat timeFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* yyyy-MM-dd HH:mm:ss
*/
static SimpleDateFormat sdfYmdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* yyyy年MM月dd日
*/
static SimpleDateFormat sdfNyr = new SimpleDateFormat("yyyy年MM月dd日");
/**
* 字符串转换为日期,格式:yyyy-MM-dd
*
* @param stringDate
* @return
*/
public static Date string2Date(String stringDate) {
Date date = null;
try {
date = sdfYmd.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 字符串转换为日期,格式:yyyy-MM-dd HH:mm:ss
*
* @param stringDate
* @return
*/
public static Date toDateYmdHms(String stringDate) {
Date date = null;
try {
date = sdfYmdhms.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将字符串的时间转换为Date类型
*
* @param operDate
* @return
*/
public static Date turnStr2Date(String operDate) {
if (StringUtil.isEmpty(operDate)) {
return null;
}
// 如果excel中的日期是2016-8-23,取出的值是42606,此数字是距离1900年1月1日的天数,以下是转换成2016-8-23格式代码
Date operDateTime;
if (StringUtil.isNumeric(operDate)) {
int operDateInt = 0;
try {
operDateInt = Integer.valueOf(operDate).intValue();
} catch (NumberFormatException e) {
e.printStackTrace();
}
Calendar c = new GregorianCalendar(1900, 0, -1);
Date time = c.getTime();
operDateTime = DateUtils.addDays(time, operDateInt); // 42605是距离1900年1月1日的天数
} else {
try {
operDateTime = StringUtil.notBlank(operDate) ? DateUtil.string2Date(operDate, "yyyy年MM月dd日") : null;
} catch (Exception e) {
operDateTime = StringUtil.notBlank(operDate) ? DateUtil.string2Date(operDate, "yyyy-MM-dd") : null;
}
}
return operDateTime;
}
/**
* 根据给定的格式,格式化字符串
*
* @param stringDate
* @param formatString
* @return
*/
public static Date string2Date(String stringDate, String formatString) {
SimpleDateFormat dd = new SimpleDateFormat(formatString);
Date date = null;
try {
date = dd.parse(stringDate);
} catch (ParseException e) {
java日期帮助类(格式化日期、获取当月第一天、获取今年某月的最后一天、获得本季度、是否闰年、获取包含今年在内的最近5年、判断指定的字符串是否是日期格式等等帮助方法,欢迎使用和指点)
最新推荐文章于 2024-07-16 05:02:05 发布
本文介绍一个Java日期帮助类,包含日期格式化、获取月份起始和结束日、判断闰年、获取最近5年范围及验证日期字符串等功能,旨在简化日期操作。
摘要由CSDN通过智能技术生成