- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- /**
- * 时间工具类
- * Created by zyb on 2016年3月15日.
- */
- public class DateTimeUtil {
- /**
- * 获取当前系统的日期和时间,返回格式为: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;
- }
- /**
- * 获取当前系统的日期和时间,返回格式为:20151023140046
- *
- * @return
- */
- public static String getDateTimeExt() {
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 获取当前系统的日期,返回格式为:2015-10-23
- *
- * @return String
- */
- public static String getDate() {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 获取当前系统的日期,返回格式为:2015/10/23
- *
- * @return
- */
- public static String getDateExt() {
- SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
- String str = df.format(new Date());
- return str;
- }
- /**
- * 当前周
- *
- * @return
- */
- public static String getWeek() {
- Calendar cd = Calendar.getInstance();
- String strWeek = String.valueOf(cd.get(Calendar.WEEK_OF_YEAR));
- return strWeek;
- }
- /**
- * 当前年
- *
- * @return
- */
- public static String getYear() {
- Calendar cd = Calendar.getInstance();
- String strYear = String.valueOf(cd.get(Calendar.YEAR));
- return strYear;
- }
- /**
- * 当前月
- *
- * @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;
- }
- /**
- * 获取当前时间差
- *
- * @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 + "小时" + min + "分" + s + "秒");
- return day;
- }
- public static void main(String[] args) throws Exception {
- System.out.println(deltaT("2016-03-11 18:02:50"));
- }
- }
【本文是51CTO专栏作者张勇波的原创文章,转载请通过51CTO获取作者授权】