日期(date)运用座谈会
前言
最近老被小伙伴戳;其实这些都是些很基础的东西,一边完善工具类;一边整理一下关于date的常见运用;以后使用起来就不需要到处去找了;争取做到想要的这儿都有。
正文
private static final String TYPE = "yyyy-MM-dd HH:mm";
public static final long ONEDAY_TIME=24*60*60*1000L;
/**
* 返回当前时间+天数
* @param nowTime 2019-01-01)
* @param number 3
* @return 2019-01-04 00:00:00
*/
public static String after(String nowTime, Integer number)
{
String time = "";
String pattern = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date now = null;
try
{
now = sdf.parse(nowTime);
}
catch (ParseException e)
{
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.DAY_OF_MONTH, number);
time = c.get(c.YEAR) + "-" + ((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1)) + "-" + (c.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + c.get(Calendar.DAY_OF_MONTH) :
c.get(Calendar.DAY_OF_MONTH)) + " " + (c.get(Calendar.HOUR_OF_DAY) < 10 ? "0" + c.get(Calendar.HOUR_OF_DAY) : c.get(Calendar.HOUR_OF_DAY)) + ":" + (c.get(Calendar.MINUTE) < 10 ? "0" + c.get(Calendar.MINUTE) : c.get(Calendar.MINUTE)) +
":" +
(c.get(Calendar.SECOND) < 10 ? "0" + c.get(Calendar.SECOND) : c.get(Calendar.SECOND));
return time;
}
/**
* 当前时间
*
* @param data
* @return
*/
public static String timeToString(Date date)
{
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
/**
* String转成规定格式
*
* @param data
* @param pattern
* @return
*/
public static String stringToTime(String data, String pattern) throws Exception
{
DateFormat fmt = new SimpleDateFormat(pattern);
Date date = fmt.parse(data);
return fmt.format(date);
}
/**
* 两个时间相减
*
* @param startTime
* @param endTime
* @return
*/
public static double jisuan(String startTime, String endTime, String pattern) throws Exception
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
long cha = end.getTime() - start.getTime();
double result = cha * 1.0 / (1000 * 60 * 60);
return result;
}
/**
* 返回固定长度的数字
*
* @param strLength
* @return
*/
public static String getFixLenthString(int strLength)
{
Random rm = new Random();
// 获得随机数
double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
// 将获得的获得随机数转化为字符串
String fixLenthString = String.valueOf(pross);
// 返回固定的长度的随机数
return fixLenthString.substring(1, strLength + 1);
}
/**
* 生成随即的名字
*
* @param fileName
* @return
*/
public static String generateFileName(String fileName)
{
String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
int random = new Random().nextInt(10000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate + random + extension;
}
/**
* 把时间格式字符串转化为date
* @param date
* @param pattern
* @return
* @throws ParseException
*/
public static Date formateDate (String date, String pattern) throws ParseException {
return new SimpleDateFormat(pattern).parse(date);
}
/**
* 获取当前年月,格式:yyyyMM
* @return java.lang.String
*/
public static String getYearAndMonth() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
Date currentTime = new Date();
String date = formatter.format(currentTime);
return date;
}
/**
* 获取当前年月,格式:yyyyMM
* @return java.lang.String
*/
public static String getYearAndMonth(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
String sdate = formatter.format(date);
return sdate;
}
/**
* 获取当前年月,格式:yyyy-MM
* @return java.lang.String
*/
public static String getYearAndMonthForSql() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
Date currentTime = new Date();
String date = formatter.format(currentTime);
return date;
}
/**
* 获取当前年月,格式:yyyy-MM
* @return java.lang.String
*/
public static String getYearAndMonthForSql(Date currentTime) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
String date = formatter.format(currentTime);
return date;
}
/**
* 获取当前年月,格式:yyyyMMdd
* @return java.lang.String
*/
public static String getYearAndMonthAndDay() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date currentTime = new Date();
String date = formatter.format(currentTime);
return date;
}
/**
* 将传入日期转换为"yyyy-MM-dd HH:mm:ss"
* @return java.lang.String
*/
public static String DateToLongString(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = formatter.format(date);
return dateStr;
}
/**
* 将传入日期转换为"yyyy-MM-dd"
* @return java.lang.String
*/
public static String DateToShortString(Date dateStr) {
SimpleDateFormat clsFormat = new SimpleDateFormat("yyyy-MM-dd");
String returnString = new String("");
returnString = clsFormat.format(dateStr);
return returnString;
}
/**
* 将传入日期转换为"MM-dd"
* @return java.lang.String
*/
public static String DateToMonthAndDayString(Date dateStr) {
SimpleDateFormat clsFormat = new SimpleDateFormat("MM-dd");
String returnString = new String("");
returnString = clsFormat.format(dateStr);
return returnString;
}
/**
* 将传入日期转换为"MM月dd日"
* @return java.lang.String
*/
public static String DateToMonthAndDayStringForZhCn(Date dateStr) {
SimpleDateFormat clsFormat = new SimpleDateFormat("MM月dd日");
String returnString = new String("");
returnString = clsFormat.format(dateStr);
return returnString;
}
/**
* 将传入日期转换为"yyyyMMdd"
* @return java.lang.String
*/
public static String DateToStringByName(Date dateStr) {
SimpleDateFormat clsFormat = new SimpleDateFormat("yyyyMMdd");
String returnString = new String("");
returnString = clsFormat.format(dateStr);
return returnString;
}
/**
* 将传入String("yyyy-MM-dd")转换为java.util.Date
* @throws ParseException
* @return java.util.Date
*/
public static Date stringToDate(String str) throws ParseException {
Date date = new Date();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
date = formater.parse(str);
return date;
}
/**
* 将传入String("yyyy-MM-dd HH:mm:ss")转换为java.util.Date
* @throws ParseException
* @return java.util.Date
*/
public static Date stringToDatetime(String str) throws ParseException {
Date date = new Date();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = formater.parse(str);
return date;
}
/**
* 将传入String("EEE MMM dd HH:mm:ss z yyyy", Locale.US)转换为java.util.Date <br />
* 主要用于Excel导入时日期格式的转化
* @throws ParseException
* @return java.util.Date
*/
public static Date stringToDateForUS(String str) throws ParseException {
Date date = new Date();
SimpleDateFormat formater = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
date = formater.parse(str);
return date;
}
/**
* 当前日期+days天 <br />
* @return java.util.Date
*/
public static Date getDateByAfter(int days) {
Calendar cal = Calendar.getInstance();
// int day=cal.get(Calendar.DATE);
cal.add(Calendar.DAY_OF_YEAR, days);
return cal.getTime();
}
/**
* 获取时间戳,格式:"yyyyMMddHHmmssSSS" <br />
* @return java.lang.String
*/
public static String getCurrTimestampForString() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取时间戳,格式:"yyyyMMddddhhmmssSSS" <br />
* @return java.lang.Integer
*/
public static Integer getCurrTimestampForInteger() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddddhhmmssSSS");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
Integer res=Integer.parseInt(dateString);
return res;
}
/**
* 当前时期+month月 <br />
* @return java.util.Date
*/
public static Date datePlusMonth(int month) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, month);
return cal.getTime();
}
/**
* 返回时间
* @param str
* @return
* @throws ParseException
*/
public static String stringToTime(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 返回日期
* @param str
* @return
* @throws ParseException
*/
public static String stringToDateString(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 返回日期 时分
* @param str
* @return
* @throws ParseException
*/
public static String stringToDateAndHourAndMinString(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 返回日期及星期
* @param str
* @return
* @throws ParseException
*/
public static String stringToDateAndWeek(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd / E");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 将秒转换为时分秒格式
* @param second
* @return
*/
public static String secondToDateTimeForMp3(int second){
String result="";
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(second * 1000);
if(second<3600){
SimpleDateFormat format = new SimpleDateFormat("mm:ss");
result=format.format(gc.getTime());
}else{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
result=format.format(gc.getTime());
}
return result;
}
/**
* 返回MM.dd
* @param str
* @return
* @throws ParseException
*/
public static String stringToMonthAndDay(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("MM.dd");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 返回MM月dd日
* @param str
* @return
* @throws ParseException
*/
public static String stringToFormatMonthAndDay(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("MM月dd日");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 返回yyyy.MM.dd
* @param str
* @return
* @throws ParseException
*/
public static String stringToFormatYearAndMonthAndDay(String str){
try {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Date date = formater.parse(str);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");
String dateString = fmt.format(date);
return dateString;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 返回日期是第几天
* @param str
* @return
* @throws ParseException
*/
public static Integer stringToDay(String str) {
try {
Date date = new Date();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
date = formater.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
} catch (ParseException e) {
e.printStackTrace();
return -1;
}
}
/**
* 返回星期几 <br/>
* 星期一 1 ~ 星期六 6 <br/>
* 星期日 0
* @param str
* @return
* @throws ParseException
*/
public static Integer stringToWeekNum(String str) {
try {
Date date = new Date();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
date = formater.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK)-1;
} catch (ParseException e) {
e.printStackTrace();
return -1;
}
}
/**
* 获取当前年月,格式:yyyy
* @return java.lang.String
*/
public static String getYear() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
Date currentTime = new Date();
String date = formatter.format(currentTime);
return date;
}
/**
* 返回某一段日期内的所有日期
* */
public static List<String> getAllInDateRange(String start_date, String end_date) {
if(StringUtils.isEmpty(start_date) || StringUtils.isEmpty(end_date)){
return null;
}
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
List<String> listDate = new ArrayList();
listDate.add(start_date);
try{
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(formatter.parse(start_date));
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(formatter.parse(end_date));
while (formatter.parse(end_date).after(calBegin.getTime())) {
calBegin.add(Calendar.DAY_OF_MONTH, 1);
listDate.add(formatter.format(calBegin.getTime()));
}
return listDate;
} catch (ParseException e){
e.printStackTrace();;
}
return null;
}
/*
* 当前日期后n天的日期
* */
public static String afterNDay(int n){
Calendar c=Calendar.getInstance();
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
c.setTime(new Date());
c.add(Calendar.DATE,n);
Date d2=c.getTime();
String s=df.format(d2);
return s;
}
public static String getDateDiff (String selfDate) {
if(selfDate == null || selfDate=="") {
return "";
}else {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = dateFormat.parse(selfDate);
} catch (ParseException e) {
e.printStackTrace();
}
long diff = new Date().getTime() - date.getTime();
long day = diff/(1000*60*60*24);
long hour = (diff - day*(1000*60*60*24))/(1000*60*60);
long minutes = (diff - day*(1000*60*60*24) - hour*(1000*60*60))/(1000*60);
String timeDiff = day+"天"+hour+"小时"+minutes+"分";
return timeDiff;
}
}
/**
* 字符串类型的时间转换时间戳
* @param date "2018-3-19 13:09:00"
* @return 1470154736000
*/
public static long getTimeLong (String date) {
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
Date d;
long time = 0;
try {
d = sdf.parse(date);
time = d.getTime();
//System.out.println(d + ": " + time);
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
/**
* 获取星期
* @param weekday
* @return
*/
public static String getStringWeekday(int weekday){
if(weekday == 1){
return "周日";
} else if(weekday == 2){
return "周一";
} else if(weekday == 3){
return "周二";
} else if(weekday == 4){
return "周三";
} else if(weekday == 5){
return "周四";
} else if(weekday == 6){
return "周五";
} else if(weekday == 7){
return "周六";
}
return "";
}
/**
* 计算两个时间 间隔了多少天
* @param beforeTime
* @param afterTime
* @return
*/
public static int getIntervalDay(long beforeTime, long afterTime){
Calendar calendar1=Calendar.getInstance();
calendar1.setTimeInMillis(beforeTime);
calendar1.set(Calendar.MILLISECOND,0);
calendar1.set(Calendar.SECOND,0);
calendar1.set(Calendar.MINUTE,0);
calendar1.set(Calendar.HOUR,0);
Calendar calendar2=Calendar.getInstance();
calendar2.setTimeInMillis(afterTime);
calendar2.set(Calendar.MILLISECOND,0);
calendar2.set(Calendar.SECOND,0);
calendar2.set(Calendar.MINUTE,0);
calendar2.set(Calendar.HOUR,0);
return (int)((calendar2.getTimeInMillis()-calendar1.getTimeInMillis())/ONEDAY_TIME);
}
/**
* 当月1日0点
* @param
* @param
* @return
*/
public static long getCurrentMonthStartTime(){
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.MILLISECOND,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.DAY_OF_MONTH,1);
return calendar.getTimeInMillis();
}
/**
* 指定月份 最后一天 0点时刻;
* @return
*/
public static long getMonthLastDayZeroTime(String month){
try {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
Date date= simpleDateFormat.parse(month);
Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(date.getTime());
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.add(Calendar.MONTH,1);
calendar.add(Calendar.DAY_OF_MONTH,-1);
return calendar.getTimeInMillis();
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 获取第二天0点时刻
* @param day
* @return
*/
public static long getNextDayZeroTime(String day){
try {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date date= simpleDateFormat.parse(day);
Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(date.getTime());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.add(Calendar.DAY_OF_MONTH,1);
return calendar.getTimeInMillis();
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
*
* @param day
* @return
*/
public static long getDayZeroTime(String day){
try {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date date= simpleDateFormat.parse(day);
Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(date.getTime());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
return calendar.getTimeInMillis();
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
*
* 获取下一个月的第一天.
*
* @return
*/
public static String getPerFirstDayOfMonth() {
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
return dft.format(calendar.getTime());
}
/**
* 今天的路径
* @return
*/
public static String addressRadom()
{
Date date = new Date();
String uploadMM = DateUtil.timeToString(date, "yyyy/MM");
String uploadDD = DateUtil.timeToString(date, "dd");
String uploadDir = uploadMM + "/" + uploadDD + "/";
return uploadDir;
}
/**
* 补0
* @param zero
* @param nikeo
* @return
*/
public static String haoAddOne(String zero,String nikeo)
{
Integer n = Integer.parseInt(nikeo);
DecimalFormat df = new DecimalFormat(zero);
return df.format(n);
}