自訂時間工具類,自訂工具類

來源:互聯網
上載者:User

自訂時間工具類,自訂工具類

package com.jredu.ch10;

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

public class DateUtil {

/**
* 返回兩個日期之間的相差天數
*
* @param d1
* @param d2
* @param patten
* @return
*/
public static int diffDay(String d1, String d2, String patten) {
int day = 0;
SimpleDateFormat format = new SimpleDateFormat(patten);
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(d1);
date2 = format.parse(d2);
long m = Math.abs(date1.getTime() - date2.getTime());
day = (int) (m / 1000 / 60 / 60 / 24);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}

/**
* 毫秒轉日期
*
* @param m
* @return
*/
public static Date getDate(long m) {
return new Date(m);
}

/**
* 返回今天的日期
*/
public static Date getCurrentDate() {
return new Date();
}

/**
* 返回當前日期加減後的日期
*
* @param isPlus
* @param day
* @return
*/
public static Date getChangeDate(boolean isPlus, int day) {
// System.currentTimeMillis()擷取目前時間的時間戳記(自1970/01/01 00:00:00開始到當前經曆的毫秒數)
long currentTime = System.currentTimeMillis();
long changeTime = 0;
if (isPlus) {
// 添加日期
changeTime = currentTime + (day * 24 * 60 * 60 * 1000);
} else {
// 減少日期
changeTime = currentTime - (day * 24 * 60 * 60 * 1000);
}
return new Date(changeTime);
}

/**
* 返回指定日期的加減天數
*
* @param isPlus
* @param day
* @param date
* @return
*/
public static Date getChangeDate(boolean isPlus, int day, Date date) {
long time = date.getTime();
long changeTime = 0;
if (isPlus) {
// 添加日期
changeTime = time + (day * 24 * 60 * 60 * 1000);
} else {
// 減少日期
changeTime = time - (day * 24 * 60 * 60 * 1000);
}
return new Date(changeTime);
}

/**
* 日期格式化
*
* @param date
* @param format
* @return
*/
public static String getFormatDate(Date date, String format) {
// 建立格式化日期對象
SimpleDateFormat sdf = new SimpleDateFormat(format);
// 將日期格式化後返回格式化字串
return sdf.format(date);
}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.