Calculate Java date

xiaoxiao2021-03-06  158

Java statistics represent the date of milliseconds from January 1, 1970. That is, for example, January 2, 1970 is 86,400,000 milliseconds after January 1. Similarly, December 31, 1969 was 86,400,000 milliseconds before January 1, 1970. Java's Date class uses the long type record these milliseconds. Because long is a symbol integer, the date can be followed before January 1, 1970. The maximum positive value and maximum negative value indicated by long types can be easily representative of 290,000,000, which is suitable for most people's time requirements. The DATE DATE class can be found in the java.util package, indicating a specified time with a value of a long type. Its useful constructor is DATE (), which creates a object that represents the time of the creation. The getTime () method returns the long value of the DATE object. In the following program, I use the DATE () constructor to create an object that represents the run time, and use the getTime () method to find the number of milliseconds represented by this date:

Import java.util. *;

Public class now {public static void main (String [] args) {date now = new date (); long nolong = now.getime (); system.out.println ("value is" nowlong);}} After running this program, I get 972, 568, 255, 150. Quickly confirm this number, at least in a reasonable range: It is less than 31 years, this value is reasonable to the time of the article on January 1, 1970, is reasonable of. The computer is this millisecond value indication time, people are reluctant to say "I will see you at 996, 321, 998, 34." Fortunately, Java provides a way to convert Date objects to strings, indicating into a traditional form. We discuss the DateFormat class in the next section, which is intuitive to create a date string. One goal of the DateFormat class DateFormat class is to create a string that people can identify. However, because of the difference in language, not all people want to see the dates of strictly identical format. The French prefer to see "25 Decembre 2000,", but Americans are used to see "DECEMBER 25, 2000." So after a DateFormat is created, this object contains the date of display format. If you use the user's computer area to set the default format, you can create a DateFormat object as follows: Use the getDateInstance () method:

DateFormat DF = DateFormat.getdateInstance (); DateFormat class can be found in the Java.Text package. Convert into strings You can use the format () method to convert the Date object as a string. The following sample program illustrates this problem:

Import java.util. *; import java.text. *;

Public class nowString {public static void main (String [] args) {date now = new date (); dateformat df = DateFormat.getdateInstance (); string s = df.format (now); system.out.println ("Today IS " s);}} In the above code, there is no parameters, using the getDateInstance () method using the default format. Java also offers several selection date formats, you can get it using the overloaded getDateInstance (int style). For convenience, DateFormat provides several preset constants where you can use these constant parameters. Below is an example of several short, medium, long, and full types: import java.util. *; Import java.text. *;

Public class styledemo {public static void main (String [] args) {date now = new date ();

DateFormat df = DateFormat.getDateInstance (); DateFormat df1 = DateFormat.getDateInstance (DateFormat.SHORT); DateFormat df2 = DateFormat.getDateInstance (DateFormat.MEDIUM); DateFormat df3 = DateFormat.getDateInstance (DateFormat.LONG); DateFormat df4 = DateFormat. getDateInstance (DateFormat.Full); string s = df.format (now); string s1 = df1.format (now); string s2 = df2.format (now); string s3 = df3.format (now); string s4 = DF4.FORMAT (now);

System.out.println ("(Default) Today is" S); System.out.Println ("Short) Today Is" S1); System.out.Println ("(Medium) Today IS" S2) System.out.Println ("(long) Today is" S3); system.out.println ("(full) Today is" S4);}} The program is as follows:

(DEFAULT) Today Is Nov 8, 2000 (SHORT) Today IS 11/8/00 (Medium) Today Is Nov 8, 2000 (Long) Today Is November 8, 2000 (FULL) Today Is Wednesday, November 8, 2000 Similar After the program, after using the default settings on my computer, the change zone is set to Sweden, and the output is as follows:

(DEFAULT) TODAY IS 2000-11-08 (Medium) Today IS 2000-NOV-08 (long) Today Is Den 8 November 2000 (FULL) Today Is Den 8 November 2000 From here You can see that Sweden's month is not capitalized (although November is still November). There is also the same, Long and Full versions are the same in Swedish, but American English is different. In addition, interesting is the Wednesday, Onsdag, Swedish words, is not included in the full date, but English is included. Note that you can use the getDateInstance () method to change the language of the DateFormat instance; however, in the above example, it is done by changing the area setting of the control panel of Windows 98. The regional settings of different places are different, and the results are different. It is good, and there is not enough. Java programmers should understand these. One benefit is that the Java programmer can only write a line of code to display the date, and the same procedure in different parts of the world will have a date format. But this is also a disadvantage that when the programmer wants to display the same format - this also has it, for example, mixed output text and date in the program, if the text is English, we don't want the date format to be other Format, like German or Spanish. If the programmer depends on the date format, the date format will be different depending on the area setting of the computer where the runtime is located. The parsing string passes the PARSE () method, and DateFormat can create a DATE object in a string. This method can throw Parsexception, so you must use the appropriate exception handling technology. The following example creates a DATE object via a string: import java.util. *; Import java.text. *;

Public class parseexample {public static void main (string [] args) {string DS = "november 1, 2000"; DATEFORMAT DF = DateFormat.getdateInstance (); try {date d = df.Parse (DS);} catch (ParseException e) {system.out.println ("Unable to Parse" DS);}}} is useful when creating an arbitrary date. I will create an arbitrary date through another way. At the same time, you will see how basic date calculations, such as another day after 90 days. You can use the GregorianCalendar class to complete this task. The GregorianCalendar class creates a way to use the GregorianCalendar class for a way to use the GregorianCalendar class, which is included in the java.util package:

Gregoriancalendar (int year, int month, int Date) Tets the month's representation, January is 0, February is 1, and so on, it is December 11. Because most people are accustomed to using words rather than using numbers, this program may be more easy to read, parent Calendar uses constants to represent months: January, February, and more. So, create Wilbur and Orville's date (December 17, 1903), you can use: Gregoriancalendar firstflight = New Gregoriancalendar (1903, Calendar.December, 17); for clear consideration, you should use the front form. However, you should also learn how to read the short format below. The following example also indicates that DECEMBER 17, 1903 (remember, in the short format, 11 means a decEmber)

Gregoriancalendar firstflight = New Gregoriancalendar (1903, 11, 17); In the previous section, you learned to convert the Date object to the string. Here you can do the same thing; but first, you need to convert the GregorianCalendar object to Date. To do this, you can use the getTime () method to inherit from its parent Calendar. The getTime () method returns the corresponding DATE object of GregorianCalendar. You can create a GregorianCalendar object, convert to the DATE object, get and output a process such as the corresponding string. Here is an example:

Import java.util. *; import java.text. *;

Public class flight {

public static void main (String [] args) {GregorianCalendar firstFlight = new GregorianCalendar (1903, Calendar.DECEMBER, 17); Date d = firstFlight.getTime (); DateFormat df = DateFormat.getDateInstance (); String s = df.format (d); System.out.Println ("First Flight WAS" S);}} Sometimes it is useful to create an instance of the GregorianCalendar class representing the current time. You can simply use the GregorianCalendar constructor without parameters, like this:

Gregoriancalendar thisday = new gregoriancalendar (); an example of output today, using GregorianCalendar object:

Import java.util. *; import java.text. *;

class Today {public static void main (String [] args) {GregorianCalendar thisday = new GregorianCalendar (); Date d = thisday.getTime (); DateFormat df = DateFormat.getDateInstance (); String s = df.format (d); System.out.println ("Today Is" s);}} Note that the Date () constructor and the GregorianCalendar () constructor are very similar: all objects are created, and the conditions are simple, representing today. Date Processing the GregorianCalendar class provides a process of processing dates. A useful method is add (). Using the add () method, you can increase the year, the number, the number of days to the date object. To use the add () method, you must provide the quantity to increase to increase. Some useful fields are DATE, MONTH, YEAR, and WEEK_OF_YEAR. The following program uses the add () method to calculate a date in the next 80 days. In Jules' is an important number, using this program to calculate the date of the Philes Fogg from the date of the day after 80 days after October 2, 1872: Import java.util. *; Import java.text. * ;

public class World {public static void main (String [] args) {GregorianCalendar worldTour = new GregorianCalendar (1872, Calendar.OCTOBER, 2); worldTour.add (GregorianCalendar.DATE, 80); Date d = worldTour.getTime (); DateFormat DF = DateFormat.getdateInstance (); string s = df.format (d); System.out.Println ("80 day trip will end" s);}} This example is imagined, but adds to a date The number of days is a universal operation: DVD can rent 3 days, library can borrow a book 21 days, stores often need to sell items within 30 days. The following program demonstrates the use annual calculation:

Import java.util. *; import java.text. *;

public class Mortgage {public static void main (String [] args) {GregorianCalendar mortgage = new GregorianCalendar (1997, Calendar.MAY, 18); mortgage.add (Calendar.YEAR, 15); Date d = mortgage.getTime (); DateFormat DF = DateFormat.getdateInstance (); string s = df.format (d); system.out.println ("15 years Mortgage Amortized on" s);}} ADD () an important side effect is its change Date. Sometimes it is important to have the original date and the revised date. Unfortunately, you can't create a GregorianCalendar object, set it and the original equivalent (Equal). The reason is that two variables point to the same Date () object address. If the DATE object changes, the two variables point to the changed date object. Instead of this approach, you should create a new object. The following program demonstrates this approach: Import java.util. *; Import java.text. *;

public class ThreeDates {public static void main (String [] args) {GregorianCalendar gc1 = new GregorianCalendar (2000, Calendar.JANUARY, 1); GregorianCalendar gc2 = gc1; GregorianCalendar gc3 = new GregorianCalendar (2000, Calendar.JANUARY, 1); // Three Dates All Equal to January 1, 2000

GC1.Add (Calendar.Year, 1); File: // GC1 and GC2 Are Changed

DateFormat DF = DateFormat.getdateInstance ();

Date D1 = gc1.gettime (); DATE D2 = gc2.gettime (); DATE D3 = GC3.GetTime ();

String S1 = DF.FORMAT (D1); String S2 = DF.FORMAT (D2); String S3 = DF.FORMAT (D3);

System.out.println ("GC1 IS" S1); System.out.Println ("GC2 IS" S2); System.out.Println ("GC3 IS" S3);}}} The program is running, GC1 and GC2 is turned into 2001 (because two objects point to the same date, but Date has been changed). The object GC3 points to a separate date, it is not changed. Calculating a review date In this section, you will see an example in accordance with the real world. This detailed program calculates a specific date. For example, you read this article, you want to remember an impressive knowledge point. If you don't have a photo of memory, you will regularly review these new information, which will help you remember it. About the review system, Kurt Hanks and Gerrel L. Pulsipher discussed in the 5 secrets of their

Public Class ReviewDates {Private Gregoriancalendar Firstday, OneQuarter, OneYear; Final Int DateArraysize = 6;

ReviewDates (Gregoriancalendar gcdate) {int year = gcdate.get (Gregoriancalendar.Year); int month = gcdate.get (Gregoriancalendar.Month); int Date = gcdate.get (Gregoriancalendar.date);

firstDay = new GregorianCalendar (year, month, date); oneDay = new GregorianCalendar (year, month, date); oneWeek = new GregorianCalendar (year, month, date); oneMonth = new GregorianCalendar (year, month, date); oneQuarter = new GregorianCalendar (year, month, date); oneYear = new GregorianCalendar (year, month, date); oneDay.add (GregorianCalendar.DATE, 1); oneWeek.add (GregorianCalendar.DATE, 7); oneMonth.add (GregorianCalendar. Month, 1); OneQuarter.add (Gregoriancalendar.month, 3); ONEYEAR.ADD (Gregoriancalendar.Year, 1);

ReviewDates () {this (new gregoriancalendar ());

public void listDates () {DateFormat df = DateFormat.getDateInstance (DateFormat.LONG); Date startDate = firstDay.getTime (); Date date1 = oneDay.getTime (); Date date2 = oneWeek.getTime (); Date date3 = oneMonth. GetTime (); Date Date4 = Onequarter.gettime (); Date Date5 = OneYear.getTime ();

String ss = df.format (startdate); string ss1 = df.format (date1); string ss2 = df.format (date2); string ss3 = df.format (date3); string ss4 = df.format (date4); String SS5 = DF.FORMAT (date5);

System.out.println ("Start Date IS"; System.out.Println ("Following Review Dates Are:"); System.out.Println (SS1); System.Out.println (SS2); System. Out.println (SS3); System.out.Println (SS4); System.out.println (SS5); System.out.println ();

public GregorianCalendar [] getDates () {GregorianCalendar [] memoryDates = new GregorianCalendar [dateArraySize]; memoryDates [0] = firstDay; memoryDates [1] = oneDay; memoryDates [2] = oneWeek; memoryDates [3] = oneMonth; memoryDates [4 ] = onequarter; memorydates [5] = oneYear; returnemorydates;}} public gregoriancalendar getfirstday () {Return this.firstday;}

Public Gregoriancalendar getoneday () {returnid.oneday;}

Public Gregoriancalendar getOndeek () {Return this.oneweek;}

Public Gregoriancalendar getonemonth () {Return this.onemonth;}

Public Gregoriancalendar getonequarter () {return this.onequarter;}

Public Gregoriancalendar getoneyEAR () {return this.oneyear;}} The following is an example of the review date using the REVIEWDATES class:

Import java.util. *;

Public class showdates {public static void main (string [] args) {reviewdates rd = new reviewdates (); rd.listdates ();

Gregoriancalendar GC = New Gregoriancalendar (2001, Calendar.january, 15); ReviewDates Jan15 = New ReviewDates (GC); Jan15.ListDates ();}} Summary This article describes 3 important classes about date processing: Date, DateFormat, Gregoriancalendar. These classes let you create a date, convert to strings, and calculate the date basic element. Processing the date in Java, this article is just the corner of the iceberg. However, the classes and methods I introduced here are more than just how you learn advanced techniques, these classes and methods can handle many usual date-related tasks 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. He has a bachelor's degree, now specializing in Java related technologies, just starting to toss in the computer field.

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

New Post(0)