JAVA對日期的相關操作

/**
 * 日期增加多少天
 * @param date 日期
 * @param days 增加的天數
 * @return
 */
public Date DateAdd(Date date,int days)
{
    Calendar   calendar   =   new   GregorianCalendar();
    calendar.setTime(date);
    calendar.add(calendar.DATE,days);//把日期往後增加一天.整數往後推,負數往前移動
    date=calendar.getTime();   //這個時間就是日期往後推一天的結果
    return  date;
}

/**
 * 根據日期獲得所在周的日期
 * @param mdate
 * @return
 */
@SuppressWarnings("deprecation")
public static List<Date> dateToWeek(Date mdate) {
    int b = mdate.getDay();
    Date fdate;
    List<Date> list = new ArrayList<Date>();
    Long fTime = mdate.getTime() - b * 24 * 3600000;

    fdate = new Date();
    fdate.setTime(fTime + (1 * 24 * 3600000));
    list.add(0, fdate);

    fdate = new Date();
    fdate.setTime(fTime + (7 * 24 * 3600000));
    list.add(1, fdate);

    return list;
}

/**
 * 比較兩個日期大小
 * @param dt1 第一個日期
 * @param dt2 第二個日期
 * @return 1:dt1>dt2  -1:dt1<dt2
 */
public static int compare_date(Date dt1,  Date dt2) {
    try {
        if (dt1.getTime() > dt2.getTime()) {
            System.out.println("dt1 在dt2前");
            return 1;
        } else if (dt1.getTime() < dt2.getTime()) {
            System.out.println("dt1 在dt2後");
            return -1;
        } else {
            return 0;
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }
    return 0;
}


/**
 * 日期轉換成字符串
 * @param date
 * @return str
 */
public static String DateToStr(Date date) {

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String str = format.format(date);
    return str;
}

/**
 * 字符串轉換成日期
 * @param str
 * @return date
 */
public static Date StrToDate(String str) {

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = format.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

public Map<String, String> getMapSendSystem() {
    return mapSendSystem;
}

public void setMapSendSystem(Map<String, String> mapSendSystem) {
    this.mapSendSystem = mapSendSystem;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章