当前位置: 移动技术网 > IT编程>开发语言>Java > java中DateUtils时间工具类详解

java中DateUtils时间工具类详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了dateutils时间工具类的具体代码,供大家参考,具体内容如下

package com.example.administrator.myapp; 
 
import java.text.parseexception; 
import java.text.simpledateformat; 
import java.util.calendar; 
import java.util.date; 
 
/** 
 * date 工具类 
 * created by lychun on 2017/12/07. 
 */ 
 
public class dateutils { 
 
  /** 
   * 得到几天前的时间 
   * 
   * @param d  时间 
   * @param day 几天 
   * @return 结果 
   */ 
  public static date getdatebefore(date d, int day) { 
    calendar now = calendar.getinstance(); 
    now.settime(d); 
    now.set(calendar.date, now.get(calendar.date) - day); 
    return now.gettime(); 
  } 
 
  /** 
   * 得到几天后的时间 
   * 
   * @param d  时间 
   * @param day 几天 
   * @return 结果 
   */ 
  public static date getdateafter(date d, int day) { 
    calendar now = calendar.getinstance(); 
    now.settime(d); 
    now.set(calendar.date, now.get(calendar.date) + day); 
    return now.gettime(); 
  } 
 
  /** 
   * 取得当前时间戳(精确到秒) 
   */ 
  public static string getcurrtimestamp() { 
    long time = system.currenttimemillis(); 
    string t = string.valueof(time / 1000); 
    return t; 
  } 
 
  /** 
   * 日期格式字符串转换成时间戳 
   * 
   * @param date_str 字符串日期 
   * @param format  如:yyyy-mm-dd hh:mm:ss 
   * @return 
   */ 
  public static string date2timestamp(string date_str, string format) { 
    try { 
      simpledateformat sdf = new simpledateformat(format); 
      return string.valueof(sdf.parse(date_str).gettime() / 1000); 
    } catch (exception e) { 
      e.printstacktrace(); 
    } 
    return ""; 
  } 
 
  /** 
   * date 转化为时间戳 
   * @param date 时间 
   * @return 
   */ 
  public static string datetimestamp(date date) { 
    return string.valueof(date.gettime() / 1000); 
  } 
 
  /** 
   * 将string转化为date 
   * 
   * @param str  字符串 
   * @param format 格式 
   * @return 结果 
   */ 
  public static date stringtodate(string str, string format) { 
    simpledateformat sdf = new simpledateformat(format);//小写的mm表示的是分钟 
    date date = null; 
    try { 
      date = sdf.parse(str); 
    } catch (parseexception e) { 
      e.printstacktrace(); 
    } 
    return date; 
  } 
 
  //将string转化为date 
  public static date stringtodate(string str) { 
    return stringtodate(str, "yyyy-mm-dd"); 
  } 
 
 
  /** 
   * 将date转化为string 
   * 
   * @param date  时间 
   * @param format 转化的格式 
   * @return 结果 
   */ 
  public static string datetostring(date date, string format) { 
    simpledateformat sdf = new simpledateformat(format); 
    string result = sdf.format(date); 
    return result; 
  } 
 
  //将时间转化为 年-月-日 的格式 
  public static string datetostring(date date) { 
    return datetostring(date, "yyyy-mm-dd"); 
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网