日期操作工具類
作者:張勇波
博主發(fā)表的文章,有的是自己原創(chuàng),有的是這些年本人從網(wǎng)上積累的,方便大家查詢。
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- /**
- * 時(shí)間工具類
- * Created by zyb on 2016年3月15日.
- */
- public class DateTimeUtil {
- /**
- * 獲取當(dāng)前系統(tǒng)的日期和時(shí)間,返回格式為:2015-10-23 14:00:46
- *
- * @return String
- */
- public static String getDateTime() {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 獲取當(dāng)前系統(tǒng)的日期和時(shí)間,返回格式為:20151023140046
- *
- * @return
- */
- public static String getDateTimeExt() {
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 獲取當(dāng)前系統(tǒng)的日期,返回格式為:2015-10-23
- *
- * @return String
- */
- public static String getDate() {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 獲取當(dāng)前系統(tǒng)的日期,返回格式為:2015/10/23
- *
- * @return
- */
- public static String getDateExt() {
- SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 當(dāng)前周
- *
- * @return
- */
- public static String getWeek() {
- Calendar cd = Calendar.getInstance();
- String strWeek = String.valueOf(cd.get(Calendar.WEEK_OF_YEAR));
- return strWeek;
- }
- /**
- * 當(dāng)前年
- *
- * @return
- */
- public static String getYear() {
- Calendar cd = Calendar.getInstance();
- String strYear = String.valueOf(cd.get(Calendar.YEAR));
- return strYear;
- }
- /**
- * 當(dāng)前月
- *
- * @return
- */
- public static String getMonth() {
- Calendar cd = Calendar.getInstance();
- String strMonth = String.valueOf(cd.get(Calendar.MONTH) + 1);
- return strMonth;
- }
- /**
- * 獲取日期
- *
- * @return
- */
- public static String getDay() {
- Calendar cd = Calendar.getInstance();
- String strDay = String.valueOf(cd.get(Calendar.DAY_OF_MONTH));
- return strDay;
- }
- /**
- * 獲取當(dāng)前時(shí)間差
- *
- * @return String
- */
- public static long deltaT(String strDateTime) {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date now = null, date = null;
- try {
- now = df.parse(getDateTime());
- date = df.parse(strDateTime);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- long l = now.getTime() - date.getTime();
- long day = l / (24 * 60 * 60 * 1000);
- long hour = (l / (60 * 60 * 1000) - day * 24);
- long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
- long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
- System.out.println("" + day + "天" + hour + "小時(shí)" + min + "分" + s + "秒");
- return day;
- }
- public static void main(String[] args) throws Exception {
- System.out.println(deltaT("2016-03-11 18:02:50"));
- }
- }
【本文是51CTO專欄作者張勇波的原創(chuàng)文章,轉(zhuǎn)載請(qǐng)通過(guò)51CTO獲取作者授權(quán)】
責(zé)任編輯:武曉燕
來(lái)源:
上下求索的Z先生博客