Java's time handling (continued <calculation java time>)

zhaozj2021-02-11  164

Java's time handling () Learn to calculate the basic time period in Java If you know how to use the date in Java, then use time and it is not as simple as it is. This article tells you how to link their differences. Robert Nielsen also tells you how to use Java to calculate the time of arrival flights and manufacturing processes. Author: Robert Nielsen Translation: Cocia Lin

This article is based on (Translator: Has translated). Here, I will list the article a few you should be familiar with the key point. If you are not very clear, I suggest you read , find out. 1. Java calculation time relies on milliseconds starting from January 1, 1970. 2. The constructor of the DATE class is Date () returns the object that represents the currently created time. Date's method getTime () returns a long value at the time or after the value of 1 January 1, 1970. 3. DateFormat class is used to convert Date to String, and vice versa. Static method getDateInstance () Returns the default format of DateFormat; getDateInstance (DateFormat.field) Returns the specified DateFormat object format. Format (Date D) Method Returns the String Representation Date, for example, "January 1, 2002." In turn, the PARSE (String S) method returns the Date object represented by the parameter string. 4. The string format returned by the format () method is different depending on the time setting of different regions. 5. GregorianCaler class has two important constructor: GregorianCalerDar (), returns objects that represent the current creating time; GregorianCalendar (int year, int month, int Date) returns objects representing any date. The GetTime () method of the GregorianCalendar class returns the date object. The add (int field, int a) method calculates the date by adding or decreasing the time, the number of days, the number or number of years. GregorianCalendar and the time two GregorianCalendar constructor 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), is created a date, hour, minute, and second:

Gregoriancalendar (int year, int month, int limited) First, I should remind each constructor requires the date information (year, month, day) in time information. If you want to say 2:30 p.m. You must point out the date. Similarly, every GregorianCalendar constructor creates a object that uses milliseconds in time. So, if your constructor is only available for the year, month, day parameters, that hours, minutes, seconds and milliseconds will be set to DateFormat and time You can use Static Method GetDateTimeInstance (int DateStyle, int TimeStyle) to create DateFormat Objects to display time and date. This method indicates the date and time format you want. If you prefer to use the default format, you can use getDatetimeInstance () instead of it. You can create a DateFormat object using a static method GetTimeInstance (int TimeStyle) 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 liftOffApollo11 ​​= 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 below: Jul 16, 1969 9:32:00 AM9: 32 AM (output according to your area) calculation interval You may sometimes need to calculate the past time; for example, give you and end time, you want to know the duration of the manufacturing process. A rental company taxes on hours or days, and the calculation time is also useful to them. Similarly, in the financial sector, important payment time is often required. Combine the problem, and human beings calculate time with two methods. You can say that the day has been over to pass 24 hours, or the calendar is turned tomorrow today. We will discuss the two situations we think. Time-segment, situation 1: Strict time in this case, only 24 hours, this day, 60 minutes, this hour is only over, this minute is only in this minute. In this method, 23 hours of time will be considered 0 days. Use this method to calculate the time period, you start from the calculated milliseconds. In order to do this, first transform each date in milliseconds from 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:" DIFCERENCE);}} The above program prints as follows: ELAPSED MILLISECONDS: 1000 This program also brings a little confusion. GREGORIANCALENDAR class getTime () returns a Date object, the GetTime () method of the DATE class returns millisecond value of the long type from January 1, 1970 to this time. Although their method name is the same, the return value is not the same! The following sequential disconnects to convert milliseconds from seconds:

Long MilliseConds = 1999; long seconds = 1999/1000; this method is to go to the fractional part to convert milliseconds to seconds, so 1,999 milliseconds are equal to 1 second, 2,000 milliseconds are equal to 2 seconds. Calculate larger units - such as days, hours, and minutes - given a time value, you can use the following procedure: 1. Calculate the largest unit, minus the number of seconds of this value 2. Calculate the second largest unit, minus this The number of seconds of the value is 3. Repeat the operation until there is only the second example, if your time is 10,000 seconds, how many hours do you want to know, how many minutes, how many seconds, you start from the largest unit: hours. 10,000 is divided by 3600 (one hour second). Using an integer division, the answer is 2 hours (integer division] to calculate the remaining seconds, 10,000- (3,600 x 2) = 2,800 seconds. So you have 2 hours and 2,800 seconds. 2,800 seconds are converted into minutes, and 2,800 is divided by 60. Using an integer division, the answer is 46.2, 800 - (60 x 46) = 40 seconds. The final 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)" " ") " Seconds " SECOND (S) ");} public static void main (String [] args {ELAPSED1 ELAP = New Elapsed1 (); ELAP.CALCHMS (10000);}} The output is as follows: 2 Hour (s) 46 minute (s) 40 second (s) The above program is even less than an hour, it can be correct Calculation hours. For example, you calculate 1,000 seconds with the above program, output into: 0 Hour (s) 16 minute (s) 40 second (s) to give an example of a real world, the following program calculates that Apollo is flying to the moon to use time :

Import java.util. *;

Public Class Lunarlanding {

Public Long getEletsedSeconds (Gregoriancalendar GC2) {date d1 = gc1.gettime (); Date D2 = gc2.gettime (); long l1 = D1.Gettime (); long l2 = d2.getime (); 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; system.out.print ("EVA DURATION ="); Apollo.calchm (EVA);

Long lunarstay = apollo.geting, lunardepartment; system.out.print ("lunar stay ="); apollo.calchm (lunarstay);}} The above program is as follows: EVA DURATION = 2 Hour (s) 13 minute ( S) Lunar stay = 21 Hour (s) 37 Minute (s) So far, our calculated base formula is this: 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 the month is 28, 29, 30, 31; one year can be 365 or 366 days. Therefore, when you try to calculate the month and year of the strict unit, the problem is produced. For example, if you use the average number of days (approximately 30.4375), and calculate the following time laptop: * July 1, 2:00 am to July 31, 10:00 Pm * February 1, 2:00 Am to February 29, 10 : 00 PM The first calculation result is 1 month; the second result is 0 months! So, the month and year in calculating strict units are going to be good. Time period, case 2: Time unit change time unit change is quite simple: If you want to count the number of days, you can simply count the number of changes. For example, if something starts on the 15th, ending on the 17th, after 2 days. (The date is first until 16, then to 17), one step at 3:25 in the afternoon, the end of 4: 10 p.m, last hour, because the hour value has changed once (from 3 to 4). Libraries often use this habitual calculation time. For example, if you pick a book from the library, I can't occupy this book at least 24 hours, I will think that the library will give you a day. Instead, I record the date I borrowed on my account. Date to become next day, I have already set this book for a day, even if I totally less than 24 hours. When the change in units is used to calculate the time period, it usually feels that there is no more than one time unit for time. For example, if 9:00 p.m. I borrowed a library book, I went back at noon next noon, I can calculate this book for a day. However, there is a feeling asking: "1 day and a few hours?" This said that the total will borrow for 15 hours, the answer is 9 hours a day? Therefore, in this article, I will calculate time with a time unit. The time algorithm for unit changes This is how you calculate the time change of the two dates: 1. Make a copy of the two dates. The close () method can make a copy. 2. Use the date copy to set all parts that are less than the time unit to its minimum unit. For example, if the number of days is calculated, then the hour, minute, seconds, and milliseconds are set to 0. In this case, the Clear () method is used to refer to their respective minimum values. 3. Remove the earlier date, add 1 unit you want to calculate, repeat until two dates. The number of you plus 1 is the answer. You can use the Before () and an AFTER () method, they returned to the Boolean value to determine if a date before or after another date. The method of the following class is used to calculate the number of days and the number of 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.hur (calendar.Hour_of_day);

gc2.clear (Calendar.MilliseCond); gc2.clear (Calendar.Second); gc2.clear (Calendar.minute); gc2.cle (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.cle (calendar.Hour_of_day); gc1.clear (Calendar.date);

GC2.Clear (Calendar.Millisecond); gc2.clear (Calendar.Second); gc2.clear (Calendar.minute); gc2.cle (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 handle hours and minutes. Similarly, the algorithm of the calculation time period can be more efficient, especially the time is very different. However, as an introduction purpose, this algorithm has a short and simple advantage. The following example uses the ELAPSEDTIME class to calculate an angel between two dates, and then 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);}} When calculating, the above program may be useful, for example, the nearest flight. It shows the output below: DAYS = 33months = 2 (OK, there is a bit exaggerated about flights; this day number algorithm is ideal for applications like libraries, what do you see how she should be cautious when working? : You see the time of the time period, you are very careful and careful consideration. This article describes two ideas of usually calculating the time period, but the calculation method of the time period that people can think of is only limited by human imagination. So, when writing a Java program, it is sure that your accuracy can satisfy the people of these programs since the use. Similarly, the thorough test procedure is not important for the process of processing time. Summary This article is based on how the Java time calculation describes how to use GregorianCalendar and DateFormat class to process time issues. You have seen two ways to think about time period issues and two corresponding ways to use Java to handle time problems. The information provided here is found to provide you with a powerful tool for processing time problems in Java.

About the author Robert Nielsen is SCJP. He has a master's degree, specializing in computer education, and teaches for many years in the computer field. He also published many computers related articles on the various magazines. About translator cocia lin (cocia@163.com) is a programmer. It has a bachelor's degree, now specializing in Java related technologies, just starting to toss in the computer field.

转载请注明原文地址:https://www.9cbs.com/read-5939.html

New Post(0)