Java time processing (continued)

Source: Internet
Author: User
Tags dateformat integer division
Java time processing (Continued <computing Java time>)
Learning to calculate basic time periods in Java
Overview
If you know how to use date in Java, it is not as easy to use time as it is. This article tells you how to link their differences.
This article is based on <computing Java time> (translated) I have published. Here, I will list several key points that you should be familiar. If you are not quite clear about these points, I suggest you read <calculate Java time> for more information.
1. Java computing time depends on the number of milliseconds since January 1, January 1, 1970.
2. The date () constructor of the date class returns the object representing the current creation time. The date method gettime () returns a long value that is equal to the time before or after January 1, January 1, 1970.
3. The dateformat class is used to convert date to string, and vice versa. The static method getdateinstance () returns the default format of dateformat; getdateinstance (dateformat. Field) returns the specified dateformat object format. The format (date d) method returns the string to represent the date. For example, the "January." method returns the date object represented by the parameter string.
4. The string format returned by the format () method varies according to the time settings in different regions.
5. the gregoriancalendear class has two important constructors: gregoriancalerdar (), which returns the object representing the current creation time; gregoriancalendar (INT year, int month, int date) returns the object representing any date. The gettime () method of the gregoriancalendar class returns the date object. The add (INT field, int amount) method calculates the date by adding or subtracting the time unit, such as the number of days, the number of months, or the number of years.
Gregoriancalendar and time
Two gregoriancalendar constructors can be used to process time. The former creates an object that represents the date, hour, and minute:

Gregoriancalendar (INT year, int month, int date, int hour, int minute)

The second one is created to indicate a date, hour, minute, and second:

Gregoriancalendar (INT year, int month, int date, int hour, int minute, int second)

First, I should remind you that every constructor requires the date information (year, month, and day) in the time information ). If you want to say p.m., you must point out the date.
Similarly, each gregoriancalendar constructor creates an object in milliseconds. Therefore, if your constructor only provides the year, month, day parameter, then the hour, minute, second, and millisecond values will be set to 0.
Dateformat and time
You can use the static method getdatetimeinstance (INT datestyle, int timestyle) to create a dateformat object to display the time and date. This method indicates the date and time format you want. If you prefer the default format, you can use getdatetimeinstance () instead.
You can use the static method gettimeinstance (INT timestyle) to create a dateformat object to display the correct time.
The following program demonstrates how getdatetimeinstance () and gettimeinstance () work:

Import java. util .*;
Import java. Text .*;

Public class Apollo {
Public static void main (string [] ARGs ){
Gregoriancalendar liftoffapolo11 = new gregoriancalendar (1969, calendar. July, 16, 9, 32 );
Date d = liftoffapollo11.gettime ();
Dateformat DF1 = dateformat. getdatetimeinstance (dateformat. Medium, dateformat. Medium );
Dateformat df2 = dateformat. gettimeinstance (dateformat. Short );
String S1 = df1.format (d );
String S2 = df2.format (d );
System. Out. println (S1 );
System. Out. println (S2 );
}
}

On my computer, the above program is shown as follows:

Jul 16,196 9 9:32:00 AM
9: 32 AM
(The output varies according to your region)

Calculation Interval
You may sometimes need to calculate the past time. For example, if you want to give you the start time and end time, you want to know the duration of the manufacturing process. A taxi company rents things by hour or day, and computing time is also very useful to them. Similarly, in the financial sector, it is often necessary to calculate the important payment time.
Complicate the problem. Humans use at least two ways to calculate time. You can say that the day has ended when 24 hours have passed, or the calendar has been switched from today to tomorrow. We will discuss the two situations we think.
Time period, Case 1: strict time unit
In this case, only 24 hours have elapsed, 60 minutes have elapsed, 60 seconds have elapsed, and so on. In this method, the time of 23 hours is considered as 0 days.
This method is used to calculate the time period from the previous milliseconds. To do this, first convert each date to the number of milliseconds that have elapsed since January 1, January 1, 1970. You can subtract the first millisecond value from the second millisecond value. Here is a simple calculation:

Import java. util .*;

Public class elapsedmillis {
Public static void main (string [] ARGs ){
Gregoriancalendar gc1 = new gregoriancalendar (1995, 11, 1, 3, 2, 1 );
Gregoriancalendar GC2 = new gregoriancalendar (1995, 11, 1, 3, 2, 2 );
// The above two dates are one second apart
Date d1 = gc1.gettime ();
Date D2 = gc2.gettime ();
Long L1 = d1.gettime ();
Long L2 = d2.gettime ();
Long Difference = L2-L1;
System. Out. println ("elapsed milliseconds:" + difference );
}
}

The above program is printed as follows:

Elapsed milliseconds: 1000

This program also brings a bit of confusion. Gettime () of the gregoriancalendar class returns a date object. The gettime () method of the date class returns the long-type millisecond value from January 1, January 1, 1970 to this time. Although their method names are the same, they return different values!
The following program segment converts milliseconds to seconds using a simple Integer Division:

Long milliseconds = 1999;
Long seconds = 1999/1000;

In this method, the decimal part is converted to milliseconds, so 1,999 milliseconds equals 1 second, and 2,000 milliseconds equals 2 seconds.
You can use the following process to calculate a larger unit, such as the number of days, hours, and minutes:
1. Calculate the maximum unit, minus the number of seconds.
2. Calculate the second unit, minus the number of seconds.
3. Repeat the operation until only seconds are left.
For example, if you want to know how many hours, minutes, And seconds are corresponding to the value of 10,000 seconds, you start from the largest unit: hours. 10,000 divided by 3600 (the number of seconds in an hour) to get the number of hours. Using Integer Division, the answer is 2 hours (rounded up in integer division) to calculate the remaining seconds, 10,000-(3,600X2) = 2,800 seconds. So you have 2 hours and 2,800 seconds.
Convert 2,800 seconds to minutes, 2,800 divided by 60. Use integer division. The answer is 46. 2,800-(60x46) = 40 seconds. The last answer is 2 hours, 46 minutes, 40 seconds.
The following Java program uses the above calculation method:

Import java. util .*;

Public class elapsed1 {
Public void calchms (INT timeinseconds ){
Int hours, minutes, seconds;
Hours = timeinseconds/3600;
Timeinseconds = timeinseconds-(hours * 3600 );
Minutes = timeinseconds/60;
Timeinseconds = timeinseconds-(minutes * 60 );
Seconds = timeinseconds;
System. Out. println (hours + "hour (s)" + minutes + "minute (s)" + seconds + "second (s )");
}

Public static void main (string [] ARGs ){
Elapsed1 elap = new elapsed1 ();
Elap. calchms (10000 );
}
}

The output result is as follows:

2 hour (s) 46 minute (s) 40 second (s)

The above program can calculate the number of hours correctly even if the time is less than one hour. For example, if you use the above program to calculate 1,000 seconds, the output is as follows:
0 hour (s) 16 minute (s) 40 second (s)
For example, in the real world, the following program calculates the time when Apollo 11 was used to fly to the moon:

Import java. util .*;

Public class lunarlanding {

Public long getelapsedseconds (gregoriancalendar gc1, gregoriancalendar GC2 ){
Date d1 = gc1.gettime ();
Date D2 = gc2.gettime ();
Long L1 = d1.gettime ();
Long L2 = d2.gettime ();
Long Difference = math. Abs (L2-L1 );
Return Difference/1000;
}

Public void calchm (long timeinseconds ){
Long hours, minutes, seconds;
Hours = timeinseconds/3600;
Timeinseconds = timeinseconds-(hours * 3600 );
Minutes = timeinseconds/60;
System. Out. println (hours + "hour (s)" + minutes + "minute (s )");
}

Public static void main (string [] ARGs ){
Gregoriancalendar lunarlanding = new gregoriancalendar (1969, calendar. July, 20, 16, 17 );
Gregoriancalendar lunardeparture = new gregoriancalendar (1969, calendar. July, 21, 13, 54 );
Gregoriancalendar starteva = new gregoriancalendar (1969, calendar. July, 20, 22, 56 );
Gregoriancalendar endeva = new gregoriancalendar (1969, calendar. July, 21, 1, 9 );

Lunarlanding Apollo = new lunarlanding ();

Long EVA = Apollo. getelapsedseconds (starteva, endeva );
System. Out. Print ("Eva duration = ");
Apollo. calchm (EVA );

Long lunarstay = Apollo. getelapsedseconds (lunarlanding, lunardeparture );
System. Out. Print ("Lunar stay = ");
Apollo. calchm (lunarstay );
}
}

The above program output is as follows:

Eva duration = 2 hour (s) 13 minute (s)
Lunar stay = 21 hour (s) 37 minute (s)

So far, the basic formula we calculated is as follows: 1 minute = 60 seconds, 1 hour = 60 minutes, 1 day = 24 hours.
"1 month =? Day, 1 year =? Day "What should I do?
The number of days in a month is 28, 29, 30, 31; a year can be 365 or 366 days. Therefore, when you try to calculate the exact unit of month and year, the problem arises. For example, if you use the average number of days of a month (approximately 30.4375) and calculate the following interval:

* July 1, A.M. to July 31, p.m.
* February 1, A.M. to February 29, P.M.

The first calculation result is 1 month, and the second result is 0 months!
Therefore, you need to think about the month and year that are strictly measured in unit time.
Time period, Case 2: time unit change
The change in time unit is quite simple: if you want to count the number of days, you can simply count the number of changes in the date. For example, if something starts on the 15th day and ends on the 17th day, it takes two days. (The date is first 16, then 17) the same, one step starts at, P. M ended and lasted 1 hour because the hour value changed once (from 3 to 4 ).
Libraries often use this habit to calculate time. For example, if you pick up a book from the library and I cannot take this book for at least 24 hours, I think the library will count you as one day. Instead, my account records the date on which I borrowed books. Since the date is changed to the next day, I have completed this book for one day, even if it is less than 24 hours in total.
When the unit change is used to calculate the time period, it is usually felt that the calculation time is not more than one time unit. For example, if I borrowed a book from the library at p.m. and went back at noon the next day, I could figure out that I had borrowed this book for a day. However, there is a feeling: "What about one day and several hours? "The answer to this question is that the total loan amount is 15 hours. What is the difference between 9 hours in a day? Therefore, in this article, I will calculate the time in a time unit change.
Time algorithm for unit change
This is how you calculate the time changes of two dates:
1. Make a copy of two dates. The close () method can be used to create a copy.
2. Use date copy to set all the parts less than the time unit change to its minimum unit. For example, if the number of days is calculated, set hours, minutes, seconds, and milliseconds to 0. In this case, use the clear () method to set the time values to their respective minimum values.
3. Retrieve the earlier date, add 1 to the unit you want to calculate, and repeat until the two dates are equal. The number of times you add 1 is the answer. You can use the before () and after () methods. They return boolean values to determine whether a date is before or after another date.
The following method is used to calculate the number of days and months.

Import java. util .*;

Public class elapsedtime {

Public int getdays (gregoriancalendar G1, gregoriancalendar G2 ){
Int elapsed = 0;
Gregoriancalendar gc1, GC2;

If (g2.after (G1 )){
GC2 = (gregoriancalendar) g2.clone ();
Gc1 = (gregoriancalendar) g1.clone ();
}
Else {
GC2 = (gregoriancalendar) g1.clone ();
Gc1 = (gregoriancalendar) g2.clone ();
}

Gc1.clear (calendar. millisecond );
Gc1.clear (calendar. Second );
Gc1.clear (calendar. Minute );
Gc1.clear (calendar. hour_of_day );

Gc2.clear (calendar. millisecond );
Gc2.clear (calendar. Second );
Gc2.clear (calendar. Minute );
Gc2.clear (calendar. hour_of_day );

While (gc1.before (GC2 )){
Gc1.add (calendar. date, 1 );
Elapsed ++;
}
Return elapsed;
}

Public int getmonths (gregoriancalendar G1, gregoriancalendar G2 ){
Int elapsed = 0;
Gregoriancalendar gc1, GC2;

If (g2.after (G1 )){
GC2 = (gregoriancalendar) g2.clone ();
Gc1 = (gregoriancalendar) g1.clone ();
}
Else {
GC2 = (gregoriancalendar) g1.clone ();
Gc1 = (gregoriancalendar) g2.clone ();
}

Gc1.clear (calendar. millisecond );
Gc1.clear (calendar. Second );
Gc1.clear (calendar. Minute );
Gc1.clear (calendar. hour_of_day );
Gc1.clear (calendar. date );

Gc2.clear (calendar. millisecond );
Gc2.clear (calendar. Second );
Gc2.clear (calendar. Minute );
Gc2.clear (calendar. hour_of_day );
Gc2.clear (calendar. date );

While (gc1.before (GC2 )){
Gc1.add (calendar. month, 1 );
Elapsed ++;
}
Return elapsed;
}
}

You can add additional methods in the above class to process hours and minutes. Similarly, algorithms can be more efficient in computing time periods, especially when time intervals are long. However, for the purpose of introduction, this algorithm has the advantages of being small and simple.
The following example uses the elapsedtime class to calculate the number of angels between two dates, followed by the number of months:

Import java. util .*;

Public class example {
Public static void main (string [] ARGs ){
Gregoriancalendar gc1 = new gregoriancalendar (2001, calendar. December, 30 );
Gregoriancalendar GC2 = new gregoriancalendar (2002, calendar. February, 1 );

Elapsedtime ET = new elapsedtime ();
Int days = ET. getdays (gc1, GC2 );
Int months = ET. getmonths (gc1, GC2 );

System. Out. println ("days =" + days );
System. Out. println ("months =" + months );
}
}

During computing, the above program may be useful, for example, the nearest flight. It displays the following output:

Days = 33
Months = 2

(OK, flight computing is a little exaggerated; this days algorithm is very suitable for applications like library borrowing books, you see how she works)
Warning
Exercise caution when working on time: it is very important to consider precisely and carefully the examples of the time period you see. This article introduces two concepts of computing time periods, but the computing methods of time periods that people can think of are limited only by human imagination.
Therefore, when writing a Java program, be sure that your accuracy can satisfy those who have used and since these programs. Similarly, a thorough testing program is not critical to the processing time program.
Summary
This article is based on my previous article on how to use the gregoriancalendar and dateformat classes to handle time issues. You have seen two ways to think about the time period problem and two corresponding ways to use Java to handle the time problem. The information provided here is very basic and provides you with a powerful tool for processing time issues in Java.

 

Related Article

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.