JAVA时间格式处理工具类

  1. 云栖社区>
  2. 博客>
  3. 正文

JAVA时间格式处理工具类

心月狐 2018-10-08 10:29:31 浏览827
展开阅读全文

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

/**
 * 默认日期格式
 */
public static String DEFAULT_FORMAT = "yyyy-MM-dd";
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat formatMs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");

/**
 * 格式化日期
 * @param date 日期对象
 * @return String 日期字符串
 */
public static String formatDate(Date date){
    SimpleDateFormat f = new SimpleDateFormat(DEFAULT_FORMAT);
    String sDate = f.format(date);
    return sDate;
}
/**
 * 格式化日期
 * @param str 日期对象
 * @return String 日期字符串
 */
public static Date formatDate(String str){
    Date date = null;
    try{
        SimpleDateFormat f = new SimpleDateFormat(DEFAULT_FORMAT);
        date = f.parse(str);
    }catch (Exception e){
        e.printStackTrace();
    }

    return date;
}

/**
 * 获取某年第一天日期
 * @param date 账期
 * @return Date
 */
public static String getYearFirst(String date){
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
    Date currYearFirst = calendar.getTime();
    return formatDate(currYearFirst);
}

/**
 * 获取上年第一天日期
 * @param date 账期
 * @return Date
 */
public static String getLastYearFirst(String date){
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
    calendar.add(Calendar.YEAR, -1);
    Date currYearFirst = calendar.getTime();
    return formatDate(currYearFirst);
}

/**
 * 获取某日的前一天日期
 * @return Date
 */
public Date getDaysBefore(String dateString, int days) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Date inputDate = dateFormat.parse(dateString);

    Calendar cal = Calendar.getInstance();
    cal.setTime(inputDate);

    int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
    cal.set(Calendar.DAY_OF_YEAR, dayOfYear - days);

    return cal.getTime();
}

/**
 * 获取某月上一个月份
 * @return Date
 */
public Date getMonthsBefore(String dateString, int months) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Date inputDate = dateFormat.parse(dateString);

    Calendar cal = Calendar.getInstance();
    cal.setTime(inputDate);

    int monthOfYear = cal.get(Calendar.MONTH);
    cal.set(Calendar.MONTH, monthOfYear - months);

    return cal.getTime();
}

/**
 * 获取某月第一天日期
 * @return Date
 */
public Date getFisrtDayOfMonth(String dateString) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
    Date inputDate = dateFormat.parse(dateString);

    Calendar cal = Calendar.getInstance();
    cal.setTime(inputDate);

    int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
    cal.set(Calendar.DAY_OF_MONTH, firstDay);

    return cal.getTime();
}

/**
 * 获取某月最后一天日期
 * @return Date
 */
public Date getLastDayOfMonth(String dateString) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
    Date inputDate = dateFormat.parse(dateString);

    Calendar cal = Calendar.getInstance();
    cal.setTime(inputDate);

    int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    cal.set(Calendar.DAY_OF_MONTH, lastDay);

    return cal.getTime();
}

/**
 * 获取最后一个月的第一天日期
 * @return Date
 */
public static String getLastMonthFirstDay() {
    Calendar cal_1 = Calendar.getInstance();
    cal_1.add(Calendar.MONTH, -1);
    cal_1.set(Calendar.DAY_OF_MONTH, 1);
    String firstDay = format.format(cal_1.getTime());
    System.out.println("-----1------firstDay:" + firstDay);

    return firstDay;
}

/**
 * 获取最后一个月最后一天日期
 * @return Date
 */
public static String getLastMonthlastDay() {
    Calendar cale = Calendar.getInstance();
    cale.set(Calendar.DAY_OF_MONTH, 0);
    String lastDay = format.format(cale.getTime());
    System.out.println("-----2------lastDay:" + lastDay);

    return lastDay;
}

/**
 * 获取当前月第一天日期
 * @return Date
 */
public static String getCurrentMonthFirstDay() {
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MONTH, 0);
    c.set(Calendar.DAY_OF_MONTH, 1);
    String first = format.format(c.getTime());
    System.out.println("===============first:" + first);
    return first;
}

/**
 * 获取当前月最后一天日期
 * @return Date
 */
public static String getCurrentMonthlastDay() {
    Calendar ca = Calendar.getInstance();
    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
    String last = format.format(ca.getTime());
    System.out.println("===============last:" + last);
    return last;
}
/**
 * 获取当前年份第一天日期
 * @return Date
 */
public static Date getCurrYearFirst() {
    Calendar currCal = Calendar.getInstance();
    int currentYear = currCal.get(Calendar.YEAR);
    return getYearFirst(currentYear);
}
/**
 * 根据传入的参数获取该年的第一天
 * @return Date
 */
public static Date getCurrYearFirst(String dateString) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date inputDate = dateFormat.parse(dateString);
    Calendar cal = Calendar.getInstance();
    cal.setTime(inputDate);
    int currentYear = cal.get(Calendar.YEAR);
    return getYearFirst(currentYear);
}
/**
 * 根据传入的参数获取该年月
 * @return Date
 */
public static String getMonth(String dateString) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("MM");
    Date inputDate = dateFormat.parse(dateString);
    Calendar cal = Calendar.getInstance();
    cal.setTime(inputDate);
    return formatDate(cal.getTime());
}
/**
 * 获取当前年份最后一天
 * @return Date
 */
public static Date getCurrYearLast() {
    Calendar currCal = Calendar.getInstance();
    int currentYear = currCal.get(Calendar.YEAR);
    return getYearLast(currentYear);
}
/**
 * 根据传入的参数获取该年
 * @return Date
 */
public static Date getYearFirst(int year) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, year);
    Date currYearFirst = calendar.getTime();
    return currYearFirst;
}

/**
 * 根据传入的参数获取该年
 * @return Date
 */
public static Date getYearLast(int year) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, year);
    calendar.roll(Calendar.DAY_OF_YEAR, -1);
    Date currYearLast = calendar.getTime();

    return currYearLast;
}
/**
 * 根据传入的参数获取该年月
 * @return Date
 */
public static String getCurrentYear(){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    Date date = new Date();
    return sdf.format(date);}
/**
 * 根据传入的参数获取该年月
 * @return Date
 */
public static String getLastYear() {
    Calendar date = Calendar.getInstance();
    date.add(Calendar.YEAR, -1);
    String year = String.valueOf(date.get(Calendar.YEAR));
    return year;
}

/**
 * 现在时间+6个月与next_time比较
 * @return
 */
public static String getStaleDated(){
    SimpleDateFormat sdfTimeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
    Date date= new Date();
    Calendar cd = Calendar.getInstance();
    cd.setTime(date);
    cd.add(Calendar.MONTH, 6);
    date=cd.getTime();
    String stale_dated = sdfTimeStamp.format(date);

    return stale_dated;
}

/**
 * 获取当前时间
 * @return
 */
public static String currentDatetime(){
    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String datetime = tempDate.format(new java.util.Date());

    return datetime;
}

/**
 * 获取当前时间
 *
 * @return
 */
public static String getYyMmtime() {
    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM");
    String datetime = tempDate.format(new java.util.Date());

    return datetime;
}

/**
 * 日期计算
 * @param date
 * @param type
 * @param number
 * @return
 */
public static String calculateDate(String date,String type,int number){

    try{

// SimpleDateFormat sdfTimeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");

        SimpleDateFormat sdfTimeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String create_time = sdfTimeStamp.format(new Date());
        Date tmpDate = sdfTimeStamp.parse(date);
        Calendar cd = Calendar.getInstance();
        cd.setTime(tmpDate);
        if(type.equals("m")){
            cd.add(Calendar.MONTH, number);
        }else if (type.equals("d")){
            cd.add(Calendar.DAY_OF_MONTH, number);
        }else {
            return "type is unknown";
        }

        tmpDate = cd.getTime();
        String dateRuslt = sdfTimeStamp.format(tmpDate);
        return dateRuslt;
    }catch(Exception ex){
        return "calculate failed";
    }

}

public static Date getDateByStr(String string){
    //String string = "2016-10-24 21:59:06";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date =null;
    try{
        date = sdf.parse(string);
        System.out.println(sdf.parse(string));
    }catch (Exception e){
        e.printStackTrace();
    }
    return date;
}

public static String getStrByDate(Date date) {
    //String string = "2016-10-24 21:59:06";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateTime = null;
    try {
        dateTime = sdf.format(date);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dateTime;
}
public static String getUpdateTime(){
    //当前时间重写更新时间
    SimpleDateFormat sdfTimeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
    String update_time = sdfTimeStamp.format(new Date());

    return update_time;
}
public static void main(String[] args) throws ParseException {

    DateUtil dateTest = new DateUtil();
    // DateFormat df = new SimpleDateFormat("yyyyMMdd");
    // Date before7Day = dateTest.getDaysBefore("20140301", 7);
    // System.out.println(df.format(before7Day));
    // Date testFirstDay = dateTest.getLastDayOfMonth("201407");
    // System.out.println(df.format(testFirstDay));
    // Date testBeforeMonth = dateTest.getMonthsBefore("20140712", 12);
    // System.out.println(df.format(testBeforeMonth));
    // DateFormat df2 = new SimpleDateFormat("yyyyMM");
    // Date getFisrtDayOfMonth = dateTest.getFisrtDayOfMonth("201407");
    // System.out.println(df2.format(getFisrtDayOfMonth));
    System.out.println(getStaleDated());

// System.out.println(formatDate(getCurrYearLast()));
// String stObj="2016-3-21";
// String[] timeDay = stObj.split("-");
// System.out.println(timeDay[1]);

}

}

网友评论

登录后评论
0/500
评论
心月狐
+ 关注