一个简单的时间工具类,后期慢慢修改完善。
package com.blsy.util;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
* 时间工具类
* */
public class DateUtils {
/**
* 获取固定格式时间字符串
* dateFormat 格式字符串 例如 yyyy-MM-dd HH:mm:ss yyyy-MM-dd
* @return
*/
public static String getTimeByForMat(String dateFormat) {
SimpleDateFormat df = new SimpleDateFormat(dateFormat);//设置日期格式
return df.format(new Date());
}
/**
* 获取固定时间格式
* dateFormat 例如 yyyy-MM-dd HH:mm:ss yyyy-MM-dd
* dateFormat 格式字符串 timeStr转换的时间
* @return
*/
public static Date getStringByForMat(String dateFormat,String timeStr) {
SimpleDateFormat df = new SimpleDateFormat(dateFormat);//设置日期格式
Date date = null;
try {
date = df.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 传入时间--返回对象可获取时间中的年月日时分秒
* 也可进行加减操作 自由选择
* @return
*/
public static Integer getTimeByForMat(Date dates) {
Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
c.setTime(dates);
int year = c.get(Calendar.YEAR);
c.add(Calendar.YEAR,1);//一年以后
int month = c.get(Calendar.MONTH);
c.add(Calendar.MONTH,3);//三个月之后的时间
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second);
Date newDate = c.getTime();//修改过后的时间
return year;
}
}