Home>

Various ways to get date time in java are shared as follows for everyone

Common time acquisition methods

public class dateutils {
  /**
   * Get timestamp
   * Output:14386928801766
   * /
  @test
  public void gettimestamp () {
    date date=new date ();
    long times=date.gettime ();
    system.out.println (times);
    //The second method:
    new date (). gettime ();
  }
  /**
   * Get formatted time
   * Output format:2015-08-04 20:55:35
   * /
  @test
  public void getformatdate () {
    date date=new date ();
    long times=date.gettime ();//time stamp
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string datestring=formatter.format (date);
    system.out.println (datestring);
  }
  /**
   * Convert timestamp to standard time
   * Output:tue oct 07 12:04:36 cst 2014
   * /
  @test
  public void timestamptodate () {
    long times=1412654676572l;
    date date=new date (times);
    system.out.println (date);
  }
}

Other ways to get time

package com.qunar.date;
import java.text.parseexception;
import java.text.parseposition;
import java.text.simpledateformat;
import java.util. *;
/**
 * created by liugen.xu on 2015/8/4.
 * /
public class dategenerate {
  /**
   * Get current time
   *
   * @return return time type yyyy-mm-dd hh:mm:ss
   * /
  public static date getnowdate () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string datestring=formatter.format (currenttime);
    parseposition pos=new parseposition (8);
    date currenttime_2=formatter.parse (datestring, pos);
    return currenttime_2;
  }
  /**
   * Get current time
   *
   * @return returns short time format yyyy-mm-dd
   * /
  public static date getnowdateshort () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    string datestring=formatter.format (currenttime);
    parseposition pos=new parseposition (8);
    date currenttime_2=formatter.parse (datestring, pos);
    return currenttime_2;
  }
  /**
   * Get current time
   *
   * @return return string format yyyy-mm-dd hh:mm:ss
   * /
  public static string getstringdate () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string datestring=formatter.format (currenttime);
    return datestring;
  }
  /**
   * Get current time
   *
   * @return returns short time string format
   * /
  public static string getstringdateshort () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    string datestring=formatter.format (currenttime);
    return datestring;
  }
  /**
   * Get time hours:minutes;seconds hh:mm:ss
   *
   * @return
   * /
  public static string gettimeshort () {
    simpledateformat formatter=new simpledateformat ("hh:mm:ss");
    date currenttime=new date ();
    string datestring=formatter.format (currenttime);
    return datestring;
  }
  /**
   * Convert long format string to time yyyy-mm-dd hh:mm:ss
   *
   * @param strdate
   * @return
   * /
  public static date strtodatelong (string strdate) {
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    parseposition pos=new parseposition (0);
    date strtodate=formatter.parse (strdate, pos);
    return strtodate;
  }
  /**
   * Convert long time format to string yyyy-mm-dd hh:mm:ss
   *
   * @param datedate
   * @return
   * /
  public static string datetostrlong (java.util.date datedate) {
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string datestring=formatter.format (datedate);
    return datestring;
  }
  /**
   * Convert short time format to string yyyy-mm-dd
   *
   * @param datedate
   * @return
   * /
  public static string datetostr (java.util.date datedate) {
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    string datestring=formatter.format (datedate);
    return datestring;
  }
  /**
   * Convert short time format string to time yyyy-mm-dd
   *
   * @param strdate
   * @return
   * /
  public static date strtodate (string strdate) {
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    parseposition pos=new parseposition (0);
    date strtodate=formatter.parse (strdate, pos);
    return strtodate;
  }
  /**
   * Get current time
   *
   * @return
   * /
  public static date getnow () {
    date currenttime=new date ();
    return currenttime;
  }
  /**
   * Extract the last day of the month
   *
   * @param day
   * @return
   * /
  public static date getlastdate (long day) {
    date date=new date ();
    long date_3_hm=date.gettime ()-3600000 * 34 * day;
    date date_3_hm_date=new date (date_3_hm);
    return date_3_hm_date;
  }
  /**
   * Get current time
   *
   * @return string yyyymmdd hhmmss
   * /
  public static string getstringtoday () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyymmdd hhmmss");
    string datestring=formatter.format (currenttime);
    return datestring;
  }
  /**
   * Get the current hour
   * /
  public static string gethour () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string datestring=formatter.format (currenttime);
    string hour;
    hour=datestring.substring (11, 13);
    return hour;
  }
  /**
   * Get the minute now
   *
   * @return
   * /
  public static string gettime () {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string datestring=formatter.format (currenttime);
    string min;
    min=datestring.substring (14, 16);
    return min;
  }
  /**
   * According to the time representation format passed by the user,Format for returning the current time.
   *
   * @param sformat yyyymmddhhmmss
   * @return
   * /
  public static string getuserdate (string sformat) {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat (sformat);
    string datestring=formatter.format (currenttime);
    return datestring;
  }
  /**
   * Difference between two hours,You must ensure that both times are in the format "hh:mm" and return character minutes
   * /
  public static string gettwohour (string st1, string st2) {
    string [] kk=null;
    string [] jj=null;
    kk=st1.split (":");
    jj=st2.split (":");
    if (integer.parseint (kk [0])<integer.parseint (jj [0]))
      return "0";
    else {
      double y=double.parsedouble (kk [0]) + double.parsedouble (kk [1])/60;
      double u=double.parsedouble (jj [0]) + double.parsedouble (jj [1])/60;
      if ((y-u)>0)
        return y-u + "";
      else
        return "0";
    }
  }
  /**
   * Get the number of days between two days
   * /
  public static string gettwoday (string sj1, string sj2) {
    simpledateformat myformatter=new simpledateformat ("yyyy-mm-dd");
    long day=0;
    try {
      java.util.date date=myformatter.parse (sj1);
      java.util.date mydate=myformatter.parse (sj2);
      day=(date.gettime ()-mydate.gettime ())/(24 * 60 * 60 * 1000);
    } catch (exception e) {
      return "";
    }
    return day + "";
  }
  /**
   * Minutes forward or backward,Where jj represents minutes.
   * /
  public static string getpretime (string sj1, string jj) {
    simpledateformat format=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    string mydate1="";
    try {
      date date1=format.parse (sj1);
      long time=(date1.gettime ()/1000) + integer.parseint (jj) * 60;
      date1.settime (time * 1000);
      mydate1=format.format (date1);
    } catch (exception e) {
    }
    return mydate1;
  }
  /**
   * Get a time delay or a few days forward,nowdate is time and delay is the number of days to move forward or backward
   * /
  public static string getnextday (string nowdate, string delay) {
    try {
      simpledateformat format=new simpledateformat ("yyyy-mm-dd");
      string mdate="";
      date d=strtodate (nowdate);
      long mytime=(d.gettime ()/1000) + integer.parseint (delay) * 24 * 60 * 60;
      d.settime (mytime * 1000);
      mdate=format.format (d);
      return mdate;
    } catch (exception e) {
      return "";
    }
  }
  /**
   * Judging whether the year
   *
   * @param ddate
   * @return
   * /
  public static boolean isleapyear (string ddate) {
    /**
     * Detailed design:1. Divided by 400 is a leap year,Otherwise:2. Leap year is not divisible by 3. Leap year is divisible by 4 and not divisible by 100.
     * 3. Dividable by 4 and divisible by 100 are not leap years
     * /
    date d=strtodate (ddate);
    gregoriancalendar gc=(gregoriancalendar) calendar.getinstance ();
    gc.settime (d);
    int year=gc.get (calendar.year);
    if ((year%400) == 0)
      return true;
    else if ((year%4) == 0) {
      if ((year%100) == 0)
        return false;
      else
        return true;
    } else
      return false;
  }
  /**
   * Returns US time format 26 apr 2006
   *
   * @param str
   * @return
   * /
  public static string getedate (string str) {
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    parseposition pos=new parseposition (0);
    date strtodate=formatter.parse (str, pos);
    string j=strtodate.tostring ();
    string [] k=j.split ("");
    return k [2] + k [1] .touppercase () + k [5] .substring (2, 4);
  }
  /**
   * Get the last day of the month
   *
   * @param dat
   * @return
   * /
  public static string getenddateofmonth (string dat) {//yyyy-mm-dd
    string str=dat.substring (0, 8);
    string month=dat.substring (5, 7);
    int mon=integer.parseint (month);
    if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
      str +="31";
    } else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
      str +="30";
    } else {
      if (isleapyear (dat)) {
        str +="29";
      } else {
        str +="28";
      }
    }
    return str;
  }
  /**
   * Determine if two times are in the same week
   *
   * @param date1
   * @param date2
   * @return
   * /
  public static boolean issameweekdates (date date1, date date2) {
    calendar cal1=calendar.getinstance ();
    calendar cal2=calendar.getinstance ();
    cal1.settime (date1);
    cal2.settime (date2);
    int subyear=cal1.get (calendar.year)-cal2.get (calendar.year);
    if (0 == subyear) {
      if (cal1.get (calendar.week_of_year) == cal2.get (calendar.week_of_year))
        return true;
    } else if (1 == subyear && 11 == cal2.get (calendar.month)) {
      //If the last week of December straddles the first week of the following year, then the last week is counted as the first week of the next year
      if (cal1.get (calendar.week_of_year) == cal2.get (calendar.week_of_year))
        return true;
    } else if (-1 == subyear && 11 == cal1.get (calendar.month)) {
      if (cal1.get (calendar.week_of_year) == cal2.get (calendar.week_of_year))
        return true;
    }
    return false;
  }
  /**
   * Generate weekly sequence,That is, what year is the current year
   *
   * @return
   * /
  public static string getseqweek () {
    calendar c=calendar.getinstance (locale.china);
    string week=integer.tostring (c.get (calendar.week_of_year));
    if (week.length () == 1)
      week="0" + week;
    string year=integer.tostring (c.get (calendar.year));
    return year + week;
  }
  /**
   * Get the date of the day of the week in which the date is
To find out what day is Monday, February 3, 2002
   *
   * @param sdate
   * @param num
   * @return
   * /
  public static string getweek (string sdate, string num) {
    //then converted to time
    date dd=dategenerate.strtodate (sdate);
    calendar c=calendar.getinstance ();
    c.settime (dd);
    if (num.equals ("1")) //returns the date on Monday
      c.set (calendar.day_of_week, calendar.monday);
    else if (num.equals ("2")) //returns the date on Tuesday
      c.set (calendar.day_of_week, calendar.tuesday);
    else if (num.equals ("3")) //returns the date on Wednesday
      c.set (calendar.day_of_week, calendar.wednesday);
    else if (num.equals ("4")) //returns the date on Thursday
      c.set (calendar.day_of_week, calendar.thursday);
    else if (num.equals ("5")) //returns the date on Friday
      c.set (calendar.day_of_week, calendar.friday);
    else if (num.equals ("6")) //returns the date on Saturday
      c.set (calendar.day_of_week, calendar.saturday);
    else if (num.equals ("0")) //returns the date on Sunday
      c.set (calendar.day_of_week, calendar.sunday);
    return new simpledateformat ("yyyy-mm-dd"). format (c.gettime ());
  }
  /**
   * Based on a date,Returns a string of the day of the week
   *
   * @param sdate
   * @return
   * /
  public static string getweek (string sdate) {
    //then converted to time
    date date=dategenerate.strtodate (sdate);
    calendar c=calendar.getinstance ();
    c.settime (date);
    //int hour=c.get (calendar.day_of_week);
    //What day is stored in hour,Its range is 1 ~ 7
    //1=Sunday 7=Saturday, etc.
    return new simpledateformat ("eeee"). format (c.gettime ());
  }
  public static string getweekstr (string sdate) {
    string str="";
    str=dategenerate.getweek (sdate);
    if ("1" .equals (str)) {
      str="Sunday";
    } else if ("2" .equals (str)) {
      str="Monday";
    } else if ("3" .equals (str)) {
      str="Tuesday";
    } else if ("4" .equals (str)) {
      str="Wednesday";
    } else if ("5" .equals (str)) {
      str="Thursday";
    } else if ("6" .equals (str)) {
      str="Friday";
    } else if ("7" .equals (str)) {
      str="Saturday";
    }
    return str;
  }
  /**
   * Days between two times
   *
   * @param date1
   * @param date2
   * @return
   * /
  public static long getdays (string date1, string date2) {
    if (date1 == null || date1.equals (""))
      return 0;
    if (date2 == null || date2.equals (""))
      return 0;
    //convert to standard time
    simpledateformat myformatter=new simpledateformat ("yyyy-mm-dd");
    java.util.date date=null;
    java.util.date mydate=null;
    try {
      date=myformatter.parse (date1);
      mydate=myformatter.parse (date2);
    } catch (exception e) {
    }
    long day=(date.gettime ()-mydate.gettime ())/(24 * 60 * 60 * 1000);
    return day;
  }
  /**
   * Form the following calendar and return a structure based on an incoming time Sunday Monday Tuesday Wednesday Thursday Friday Saturday Below are the various times of the month
   * This function returns the date of the first Sunday of the calendar
   *
   * @param sdate
   * @return
   * /
  public static string getnowmonth (string sdate) {
    //take the first day of the month
    sdate=sdate.substring (0, 8) + "01";
    //Get the day of the week on the 1st of this month
    date date=dategenerate.strtodate (sdate);
    calendar c=calendar.getinstance ();
    c.settime (date);
    int u=c.get (calendar.day_of_week);
    string newday=dategenerate.getnextday (sdate, (1-u) + "");
    return newday;
  }
  /**
   * Get the database primary key.Generate the format as yyyymmddhhmmss + k-bit random number.
   *
   * @param k means take a few random numbers,You can set it yourself
   * /
  public static string getno (int k) {
    return getuserdate ("yyyymmddhhmmss") + getrandom (k);
  }
  /**
   * Returns a random number
   *
   * @param i
   * @return
   * /
  public static string getrandom (int i) {
    random jjj=new random ();
    //int suijishu=jjj.nextint (9);
    if (i == 0)
      return "";
    string jj="";
    for (int k=0;k<i;k ++) {
      jj=jj + jjj.nextint (9);
    }
    return jj;
  }
  /**
   * /
  public static boolean rightdate (string date) {
    simpledateformat sdf=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    ;
    if (date == null)
      return false;
    if (date.length ()>10) {
      sdf=new simpledateformat ("yyyy-mm-dd hh:mm:ss");
    } else {
      sdf=new simpledateformat ("yyyy-mm-dd");
    }
    try {
      sdf.parse (date);
    } catch (parseexception pe) {
      return false;
    }
    return true;
  }
  /**
   * ************************************************** ***********************
   * //nd=1 means the returned value contains the year //yf=1 means the returned value contains the month //rq=1 means the returned value contains the date //format means the returned format 1
   * Returns in Chinese in the year, month, day 2 Returns with a horizontal line-//3 Returns with a slash/Return 4 Returns with an abbreviation without other symbols //5 with a dot
   * ********************************************** ***********************
   * /
  public static string getstringdatemonth (string sdate, string nd, string yf, string rq, string format) {
    date currenttime=new date ();
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    string datestring=formatter.format (currenttime);
    string s_nd=datestring.substring (0, 4);//year
    string s_yf=datestring.substring (5, 7);//month
    string s_rq=datestring.substring (8, 10);//date
    string sreturn="";
    roc.util.mychar mc=new roc.util.mychar ();
    if (sdate == null || sdate.equals ("") ||! mc.isdate (sdate)) {//handle null case
      if (nd.equals ("1")) {
        sreturn=s_nd;
        //handle break
        if (format.equals ("1"))
          sreturn=sreturn + "year";
        else if (format.equals ("2"))
          sreturn=sreturn + "-";
        else if (format.equals ("3"))
          sreturn=sreturn + "/";
        else if (format.equals ("5"))
          sreturn=sreturn + ".";
      }
      //handle month
      if (yf.equals ("1")) {
        sreturn=sreturn + s_yf;
        if (format.equals ("1"))
          sreturn=sreturn + "month";
        else if (format.equals ("2"))
          sreturn=sreturn + "-";
        else if (format.equals ("3"))
          sreturn=sreturn + "/";
        else if (format.equals ("5"))
          sreturn=sreturn + ".";
      }
      //processing date
      if (rq.equals ("1")) {
        sreturn=sreturn + s_rq;
        if (format.equals ("1"))
          sreturn=sreturn + "day";
      }
    } else {
      //is not a null value,Is also a valid date value,First convert it to a standard time format
      sdate=roc.util.rocdate.getokdate (sdate);
      s_nd=sdate.substring (0, 4);//year
      s_yf=sdate.substring (5, 7);//month
      s_rq=sdate.substring (8, 10);//date
      if (nd.equals ("1")) {
        sreturn=s_nd;
        //handle break
        if (format.equals ("1"))
          sreturn=sreturn + "year";
        else if (format.equals ("2"))
          sreturn=sreturn + "-";
        else if (format.equals ("3"))
          sreturn=sreturn + "/";
        else if (format.equals ("5"))
          sreturn=sreturn + ".";
      }
      //handle month
      if (yf.equals ("1")) {
        sreturn=sreturn + s_yf;
        if (format.equals ("1"))
          sreturn=sreturn + "month";
        else if (format.equals ("2"))
          sreturn=sreturn + "-";
        else if (format.equals ("3"))
          sreturn=sreturn + "/";
        else if (format.equals ("5"))
          sreturn=sreturn + ".";
      }
      //processing date
      if (rq.equals ("1")) {
        sreturn=sreturn + s_rq;
        if (format.equals ("1"))
          sreturn=sreturn + "day";
      }
    }
    return sreturn;
  }
  public static string getnextmonthday (string sdate, int m) {
    sdate=getokdate (sdate);
    int year=integer.parseint (sdate.substring (0, 4));
    int month=integer.parseint (sdate.substring (5, 7));
    month=month + m;
    if (month<0) {
      month=month + 12;
      year=year-1;
    } else if (month>12) {
      month=month-12;
      year=year + 1;
    }
    string smonth="";
    if (month<10)
      smonth="0" + month;
    else
      smonth="" + month;
    return year + "-" + smonth + "-10";
  }
  public static string getokdate (string sdate) {
    if (sdate == null || sdate.equals (""))
      return getstringdateshort ();
    if (! vestr.isdate (sdate)) {
      sdate=getstringdateshort ();
    }
    //convert "/" to "-"
    sdate=vestr.replace (sdate, "/", "-");
    //if it is only 8 bits long, it is converted
    if (sdate.length () == 8)
      sdate=sdate.substring (0, 4) + "-" + sdate.substring (4, 6) + "-" + sdate.substring (6, 8);
    simpledateformat formatter=new simpledateformat ("yyyy-mm-dd");
    parseposition pos=new parseposition (0);
    date strtodate=formatter.parse (sdate, pos);
    string datestring=formatter.format (strtodate);
    return datestring;
  }
  public static void main (string [] args) throws exception {
    try {
      //system.out.print(integer.valueof(gettwoday("2006-11-03 12:22:10 "," 2006-11-02 11:22:09 ")));
    } catch (exception e) {
      throw new exception ();
    }
    //system.out.println("sss ");
  }
}

We have a basic grasp of the way java obtains the date and time.You?

  • Previous jQuery click to change class and toggle and toggleClass () method definition usage
  • Next Simple analysis of C language program compilation problems for the ARM platform