Provides you with a good time tool class datetime

Source: Internet
Author: User
Tags time in milliseconds

This kind of inspiration comes from C #

Although there are some date4j on the internet, jar is too tangled. The source code can be inherited into your util package. As a Senior Programmer, I believe there are many good util tool classes, I also hope that through this sharing, the technical experts will be able to share their useful tools.

First look at the source code

/** Ansitech Development Platform (Java) SDK ** copyright (c) 2014, ansitech Network Technology Co ., ltd All Rights Reserved. * http://www.ansitech.com/java/sdk/ ** licensed under the Apache license, version 2.0 (the "License"); * you may not use this file license t in compliance with the license. * You may obtain a copy of the license at ** http://www.apache.org/licenses/LICENSE-2.0 ** unless required by applicable la W or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * Without warranties or conditions of any kind, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */package COM. ansitech. core. system; import Java. io. serializable; import Java. text. dateformat; import Java. text. parseexcep Tion; import Java. text. simpledateformat; import Java. util. calendar; import Java. util. date;/***** Date and Time ** <p> encapsulation of calendar, for ease of use </P> ** @ author qsyang * @ version 1.0 */public class datetime implements serializable {/*** yyyy-mm-dd hh: mm: SS format */public static final string default_date_time_format_pattern = "yyyy-mm-dd hh: mm: SS";/*** yyyy-mm-dd hh: MM format */public static final string default_date_t Ime_hhmm_format_pattern = "yyyy-mm-dd hh: mm "; /*** yyyy-mm-dd hh format */public static final string default_date_time_hh_format_pattern = "yyyy-mm-dd hh "; /*** yyyy-mm-dd format */public static final string default_date_format_pattern = "yyyy-mm-dd";/*** hh: mm: SS format */public static final string default_time_format_pattern = "HH: mm: SS";/*** hh: Mm format */public static final string default_time_hhmm _ Format_pattern = "HH: mm";/*** year * <p> you can use datetime. now (). get (datetime. year_field) to obtain the year of the current time </P> */public static final int year_field = Java. util. calendar. year;/* month * <p> you can use datetime. now (). get (datetime. month_field) to obtain the month of the current time </P> */public static final int month_field = Java. util. calendar. month;/*** day * <p> can be passed by datetime. now (). get (datetime. day_field) to get the day of the current time </P> */public static final int day _ Field = Java. util. calendar. date;/*** hour <p> you can use datetime. now (). get (datetime. to get the hour of the current time </P> */public static final int hour_field = Java. util. calendar. hour_of_day;/*** minute <p> you can use datetime. now (). get (datetime. minute_field) to obtain the minute of the current time </P> */public static final int minute_field = Java. util. calendar. minute;/*** seconds * <p> you can use datetime. now (). get (datetime. second_field) to obtain the seconds of the current time </P> */Public St Atic final int second_field = Java. util. calendar. second;/*** millisecond <p> can be passed through datetime. now (). get (datetime. millisecond_field) to obtain the current time in milliseconds </P> */public static final int millisecond_field = Java. util. calendar. millisecond; private Java. util. calendar C; // calendar class/*** get a datetime, which has not been initialized yet, indicating that the time is 00:00:00. 000 * <p> to obtain the current system time, use datetime. now (); </P> */Public datetime () {c = calendar. getinstance (); c. Clear ();}/*** set the time <p> to input a time object, will be converted to the datetime type </P> ** @ Param date time object */Public datetime (Java. util. date) {c = calendar. getinstance (); C. settime (date);}/*** set time <p> You can input a Calendar Object, will be converted to the datetime type </P> ** @ Param calendar Calendar Object */Public datetime (Java. util. calendar calendar) {This. C = calendar;}/*** get current system time ** @ return datetime current system time */public static datetime now () {calendar Cale Ndar = calendar. getinstance (); return New datetime (calendar);}/*** set the time in milliseconds. The time base is 00:00:00. 000; <p> for example, new datetime (1000) * Indicates 00:00:01. 000; <br> use a negative number to indicate the time before the base time </P> ** @ Param milliseconds millisecond */Public datetime (long milliseconds) {c = calendar ar. getinstance (); C. settimeinmillis (milliseconds);}/*** convert to date type ** @ return date time */public date todate () {return C. gettime ();}/* ** Convert to a Calendar Object ** @ return Calendar Object */Public Java. util. calendar tocalendar () {return C;}/*** converts to Java. SQL. date (yyyy-mm-dd) date ** @ return Java. SQL. date */Public Java. SQL. date tosqldate () {return New Java. SQL. date (C. gettimeinmillis ();}/*** converts to Java. SQL. time (HH: mm: SS) Time ** @ return Java. SQL. time */Public Java. SQL. time tosqltime () {return New Java. SQL. time (C. gettimeinmillis ());}/*** Convert to Java. SQL. timestamp (timestamp) ** @ return Java. SQL. timestamp timestamp */Public Java. SQL. timestamp tosqltimestamp () {return New Java. SQL. timestamp (C. gettimeinmillis ();}/*** parse time <p> convert to HH: mm: SS or hh: MM format </P> ** @ Param time string format time * @ return datetime Date and Time object */public static datetime parsetime (string time) throws Java. text. parseexception {try {return datetime. par Sedatetime (time, datetime. default_time_format_pattern);} catch (parseexception e) {return datetime. parsedatetime (time, datetime. default_time_hhmm_format_pattern );}} /*** parse the date <p> according to the default_date_format_pattern rule in datetime, convert it to the yyyy-mm-dd format </P> ** @ Param date string format date * @ return datetime date time class */public static datetime parsedate (string date) throws Java. text. parseexception {return datetime. parsedat Etime (date, datetime. default_date_format_pattern);}/*** parse the datetime <p> according to the default_date_time_format_pattern rule in datetime, convert it to yyyy-mm-dd * hh: mm: SS format </P> ** @ Param datetime string format date and time * @ return datetime Date and Time object */public static datetime parsedatetime (string datetime) throws Java. text. parseexception {datetime result = NULL; // try to press yyyy-mm-dd hh: mm: Ss to analyze try {result = datetime. parsedatetime (datetime, datetime. Default_date_time_format_pattern);} catch (parseexception e) {// resolution error result = NULL;} // try to analyze if (null = Result) by using yyyy-mm-dd hh: mm) {try {result = datetime. parsedatetime (datetime, datetime. default_date_time_hhmm_format_pattern);} catch (parseexception e) {// resolution error result = NULL ;}// try to analyze if (null = Result) by using yyyy-mm-dd hh) {try {result = datetime. parsedatetime (datetime, datetime. default_date _ Time_hh_format_pattern);} catch (parseexception e) {// resolution error result = NULL ;}// try to analyze if (null = Result) by yyyy-mm-dd) {try {result = datetime. parsedate (datetime);} catch (parseexception e) {// resolution error result = NULL;} // try to analyze by time if (null = Result) {result = datetime. parsetime (datetime);} return result;}/*** use the specified pattern to analyze the string <p> for the usage of pattern, see Java. text. simpledateformat </P> ** @ Param datetime String format date and time * @ Param pattern Date Parsing Rule * @ return datetime Date and Time object * @ see Java. text. simpledateformat */public static datetime parsedatetime (string datetime, string pattern) throws Java. text. parseexception {simpledateformat FMt = (simpledateformat) dateformat. getdateinstance (); FMT. applypattern (pattern); return New datetime (FMT. parse (datetime);}/*** convert to the default_date_format_pattern (yyyy-mm-dd) Format String ** @ Return yyyy-mm-dd format string */Public String todatestring () {return todatetimestring (datetime. default_date_format_pattern);}/*** convert to default_time_format_pattern (HH: mm: SS) Format String ** @ return hh: mm: SS format string */Public String totimestring () {return todatetimestring (datetime. default_time_format_pattern);}/*** converts it to a default_date_time_format_pattern (yyyy-mm-dd hh: mm: SS) Format String ** @ return yyyy-mm-d D hh: mm: SS format string */Public String todatetimestring () {return todatetimestring (datetime. default_date_time_format_pattern);}/*** use date to convert pattern <p> for the usage of pattern, see Java. text. simpledateformat </P> ** @ Param pattern Date Parsing Rule * @ return date and time string converted by Rule */Public String todatetimestring (string pattern) {simpledateformat FMt = (simpledateformat) dateformat. getdateinstance (); FMT. applypattern (pattern); Return FMT. format (C. gettime ();}/*** get the value of a metric of the time represented by datetime. ** @ Param field INT: <br> datetime. year_field -- returns the year <br> * datetime. month_field -- returns the month, 1 in December, 2 in December, and so on. <br> datetime. day_field -- * returns the current day (in this month) <br> datetime. hour_field -- returns the hour (in the current day), in the 24-hour format <br> * datetime. minute_field -- returns the number of minutes (in this hour) <br> datetime. second_field -- * returns the number of seconds (in this minute) <br> datetime. millisecond_field -- returns the number of milliseconds (in this second) * @ return int Field Value */Public int get (INT field) {// The month needs to be + 1 (the month starts from 0) if (datetime. month_field = field) {return C. get (field) + 1;} else {return C. get (field) ;}}/*** returns the number of milliseconds since. ** @ return long milliseconds */public long gettimeinmillis () {return C. gettimeinmillis ();}/*** set the field value ** @ Param field int to: <br> datetime. year_field -- year <br> * datetime. month_field-month, which starts from 1 in January <br> dateti Me. day_field -- * current day (in this month) <br> datetime. hour_field -- hour (in this day), in 24-hour format <br> * datetime. minute_field -- number of minutes (in this hour) <br> datetime. second_field -- * seconds (in this minute) <br> datetime. millisecond_field -- millisecond count (in this second) * @ Param value */Public void set (INT field, int value) {// The month needs to be-1 (the month starts from 0) if (datetime. month_field = field) {C. set (field, value-1);} else {C. set (field, value) ;}}/*** set the year, month, and day of the datetime date **@ Param year * @ Param month * @ Param day */Public void set (INT year, int month, int day) {set (datetime. year_field, year); Set (datetime. month_field, month); Set (datetime. day_field, day );} /*** set the year, month, day, and hour of the datetime date ** @ Param year * @ Param month * @ Param day * @ Param hour */Public void set (INT year, int month, int day, int hour) {set (year, month, day); Set (datetime. hour_field, ho UR );} /*** set the year, month, day, hour, and minute of the datetime date ** @ Param year * @ Param month * @ Param day * @ Param hour *@ param minute */Public void set (INT year, int month, int day, int hour, int minute) {set (year, month, day, hour); Set (datetime. minute_field, minute );} /*** set the year, month, day, hour, minute, and second of the datetime date ** @ Param year * @ Param month * @ Param day * @ Param hour * @ Param minute * @ Param second */Public void set (INT year, int month, int day, int hour, int minute, int second) {set (year, month, day, hour, minute ); set (datetime. second_field, second );} /*** set the year, month, day, hour, minute, second, or millisecond of the datetime date ** @ Param year * @ Param month * @ Param day * @ Param hour hour * @ Param minute * @ Param second * @ Param millisecond */Public void set (INT year, int month, int day, int hour, int minute, int Second, int millisecond) {set (year, month, day, hour, minute, second); Set (datetime. millisecond_field, millisecond);}/*** the addition of Field Values <p> Add () is very powerful. Add can calculate datetime fields. <Br> * If You Need to subtract a value, you can use a negative value, for example, add (field,-value ). <Br> * or call datetime. reduce (INT, INT) minus date </P> ** @ Param field int value: <br> datetime. year_field -- year <br> * datetime. month_field -- month, which starts from 1 in January <br> * datetime. day_field -- current day (in this month) <br> * datetime. hour_field -- hour (in this day), in 24-hour format <br> * datetime. minute_field -- number of minutes (in this hour) <br> * datetime. second_field -- number of seconds (in this minute) <br> * datetime. millisecond_field -- number of milliseconds (in this second) * @ Param amount number (if the number is smaller than 0, it is subtract) */Public voi D add (INT field, int amount) {C. add (field, amount);}/*** subtract Field Values <p> encapsulate the add () function. Add can calculate the fields in the calendar. <Br> * If You Need to subtract a value, you can use a negative value, for example, add (field,-value ). <Br> * For detailed usage, see calendar. add (INT, INT) </P> ** @ Param field int value: <br> datetime. year_field -- year <br> * datetime. month_field -- month, which starts from 1 in January <br> * datetime. day_field -- current day (in this month) <br> * datetime. hour_field -- hour (in this day), in 24-hour format <br> * datetime. minute_field -- number of minutes (in this hour) <br> * datetime. second_field -- number of seconds (in this minute) <br> * datetime. millisecond_field -- millisecond count (in this second) * @ Param amount count (if the number is smaller than 0, it is the sum) */Public void limit C E (INT field, int amount) {C. add (field,-amount);}/*** determines whether the time indicated by datetime is after the time indicated by the specified object, and returns the judgment result. <P> This method is equivalent to: compareto (when) *> 0 <br> true is returned only when is a datetime instance. Otherwise, false is returned. ** @ Param when: object to be compared * @ return if the datetime time is after the time indicated by when, true is returned; otherwise, false is returned. */Public Boolean after (object when) {If (when instanceof datetime) {return C. after (datetime) When ). c);} return C. after (when);}/*** determines whether the time indicated by datetime is before the time indicated by the specified object, and returns the judgment result. <P> This method is equivalent to: compareto (when) * <0 <br> true is returned only when is a datetime instance. Otherwise, false is returned. </P> ** @ Param when: object to be compared * @ return if the calendar time is earlier than the time indicated by when, true is returned; otherwise, false is returned. */Public Boolean before (object when) {If (when instanceof datetime) {return C. before (datetime) When ). c);} return C. before (when);}/*** create and return a copy of this object ** @ return date and time object */@ override public object clone () {return New datetime (calendar) C. clone ();}/*** returns the hash code of this calendar ** @ return the hash code value of this object. * @ See object */@ override public int hashcode () {return C. hashcode ();}/*** compares this datetime with the specified object. ** @ Param obj-object to be compared. * @ Return if this object is equal to OBJ, true is returned; otherwise, false is returned. * @ See object */@ override public Boolean equals (Object OBJ) {If (OBJ instanceof datetime) {return C. equals (datetime) OBJ ). tocalendar ();} If (OBJ instanceof calendar) {return C. equals (OBJ);} If (OBJ instanceof Java. util. date) {return C. gettime (). equals (OBJ) ;}return false ;}}
Next let's take a look at how to use it:

Obtain the current system time: datetime. Now (); returns a datetime object.

A datetime object can be converted into various date formats we need,

Example: Java. util. Date

DateTime.now().toDate();
You may also think that this writing method is not directly new date (); isn't it fast.

In many cases, a string needs to be converted to a java. util. date object. What should we do?

<pre name="code" class="java">new DateTime("2014-10-29").toDate();
Of course. 

new DateTime("2014-10-29 15:19:23").toDate();
Here is only the basic usage. In other cases, java. util. date is converted into a string format.

We may usually use simpledateformat, but this is too troublesome. Let's look at the simple method.

new DateTime(new Date()).toDateString();
Returns a string in the format.

new DateTime(new Date()).toDateTimeString();
The returned string is a string in the format of 15:23:23.

What should we do if we need a format similar to October 29, 2014 or October 29, 2014?

New datetime (new date ()). todatetimestring ("mm DD, YYYY"); New datetime (new date ()). todatetimestring ("mm minute SS seconds on mm dd, YYYY ");
That's all!

There are many other functions. I will not give them one by one here. If you think it is good, please support them and leave a comment or share it with other friends, let more people know.

My motivation for writing articles comes from your support and your visits!

Thank you for reading this article. Thank you!





Provides you with a good time tool class datetime

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.