How to use the date and calender classes in Java

Source: Internet
Author: User
Tags date now dateformat integer numbers set time time and date

View Articles
How to use date and calender classes in Java 2009-10-04 20:49

Date and calendar are classes that provide time processing in the Java class Library, and because dates occupy an important place in the application of business logic, here you want to do a basic explanation of these two classes, because the technology is limited, please correct me.
The date class, as the name implies, is known as a date-related class, the main function of this class is to get the current time, but this class also has set time and some other functions, but because of its own design problems, these methods have been criticized many, And these critical features have been ported to another class, and that's the second class we're going to talk about today.
Before talking about two classes, there is one more class, that is, the DateFormat class, which is used to format the date and will be discussed later.
First, let's look at an example of getting the current time:
Date date = new Date ();
System.out.println (Date.gettime ()); The above statement first creates an object of date, and then uses the GetTime method to get the current time, but notice that the output is indeed a string of long integer numbers, which is why? In fact, this is the system based on the current time calculation of a long type of number, as to how the calculation is not described in this article, then how to show the correct time? This is going to take advantage of the DateFormat class above, this class is a base class, it has a subclass is SimpleDateFormat, the concrete usage see the following code:
Date date = new Date ();
SimpleDateFormat DATEFM = new SimpleDateFormat ("eeee-mmmm-dd-yyyy");
System.out.println (Datefm.format (date)); This code begins to create a Date object that gets the current time, and the focus is on the SimpleDateFormat object behind it. This pair inherits the DateFormat, formats the date object with the Format method, and then outputs, and the format customization is customized by the user, eeee represents the week, mmmm represents the month, and DD represents the day, yyyy represents the year. Using this method, the output time can be based on a user-defined format.
The above describes the output time by the user-defined format, the following will be introduced in the Java class Library to provide the standard format output time, which will use the DateFormat class, see the following code:
Date date = new Date ();
DateFormat DATEFM = dateformat.getdatetimeinstance (Dateformat.short,
Dateformat.short);
System.out.println (Datefm.format (date)); The method used here is the same as the user-defined method, except that an abstract class is used here, because DateFormat is an abstract class, so it cannot construct objects through constructors, In this case, the object is obtained through the Getdatetimeinstance () method, and the parameters passed are the constants defined in the DateFormat, and the system outputs the current time based on these constants, because the Getdatetimeinstance method is used here, Therefore, two constant parameters are passed to format the date and the current time, respectively.
The above describes how to get the system time and how to format the output, what if you want to get or set a part of the time? For example, year, month, day. This is going to depend on the Calendar class, this class is an abstract class, it has a subclass GregorianCalendar, and then I will use this subclass to demonstrate the process, see the following code:

DateFormat DateFormat = dateformat.getdateinstance (dateformat.full);
GregorianCalendar cal = new GregorianCalendar ();
Cal.settime (New Date ());
System.out.println ("System Date:" + Dateformat.format (Cal.gettime ()));
Cal.set (Gregoriancalendar.day_of_week,gregoriancalendar.friday);
System.out.println ("After Setting day of Week to Friday:" +
Dateformat.format (Cal.gettime ()));
In this code, you first create a DateFormat object for formatting, then create a GregorianCalendar object cal, and then use the Cal.settime () method to set the time in the Cal object to the current time, The time returned by Cal.gettime () is then formatted by format, and the date of the CAL is set by the set method, which is the Friday of the current week, when the time stored in the CAL is the moment of Friday, and then the output is formatted with format. If the current time is 11:30 on the January 27, 2005 of the Week 4, then the last sentence will be output January 28, 2005 5 11:30.


After JDK 1.1, most methods of the java.util.Date type are deprecated. Instead of it is the calendar.

And between Java.sql.Date and java.util.Date, there are subtle relationships.

How to insert the date type into the database is a great barrier to many people.

We will discuss the following classes:

1, Concrete Class (and abstract class relative) Java.util.Date
2. Abstract class Java.text.DateFormat and a specific subclass of it, Java.text.SimpleDateFormat
3. Abstract class Java.util.Calendar and a specific subclass of it, Java.util.GregorianCalendar

A specific class can be instantiated, but an abstract class cannot. You must first implement a specific subclass of the abstract class.

The date class began to evolve from the Java Development Package (JDK) 1.0, when it contained only a few methods of acquiring or setting up parts of a date data, such as month, day, and year. These methods have now been criticized and have been transferred to the Calendar class, which we will discuss further in this article. This improvement is designed to better handle the internationalization format of date data. Just like in JDK 1.1, the Date class is really just a package class that contains a long integer that represents the number of milliseconds from GMT (Greenwich Mean Time) 1970, January 1 00:00:00, before or after that moment.

First, create a Date object R

Let's look at a simple example that creates a Date object using the system's current date and time and returns a long integer. This time is often referred to as the system time of the Java Virtual Machine (JVM) host environment.
Import Java.util.Date;

public class DateExample1 {
public static void Main (string[] args) {
Get the System Date/time
Date date = new Date ();

System.out.println (Date.gettime ());
}
}

In Saturday, September 29, 2001, the afternoon is about 6:50, the above example shows the result on the system output device is 1001803809710. In this case, it is worth noting that we created a Date object using the date constructor, which does not accept any arguments. This constructor uses the System.currenttimemillis () method internally to get the date from the system.

Well, now we know how to get the number of milliseconds that have been going on since January 1, 1970. How can we display this date in a user-aware format? Here the class Java.text.SimpleDateFormat and its abstract base class Java.text.DateFormat come in handy.

II. custom format for date data

If we want to customize the format of date data, for example Saturday-September-29th-2001. The following example shows how to do the work:

Import Java.text.SimpleDateFormat;
Import Java.util.Date;

public class DateExample2 {

public static void Main (string[] args) {

SimpleDateFormat Bartdateformat =
New SimpleDateFormat ("eeee-mmmm-dd-yyyy");

Date date = new Date ();

System.out.println (Bartdateformat.format (date));
}
}

As long as you pass the format string "eee-mmmm-dd-yyyy" to the SimpleDateFormat constructor, we can specify the format we want. You should be able to see that the ASCII characters in the format string tell the Format function which part of the date data is displayed below. Eeee is the week, MMMM is the month, DD is the day, YYYY is the year. The number of characters determines how the date is formatted. Passing "Ee-mm-dd-yy" displays sat-09-29-01. Please see Sun's Web site for full instructions on getting the date formatting options.

Iii. parsing text data into date objects R

Suppose we have a text string that contains a formatted date object, and we want to parse the string and create a Date object from the text date data. We will again call the SimpleDateFormat class with the formatted string "MM-DD-YYYY", but this time we use format parsing instead of generating a text date data. Our example, shown below, will parse the text string "9-29-2001" and create a Date object with a value of 001736000000.

Example program:

Import Java.text.SimpleDateFormat;
Import Java.util.Date;

public class DateExample3 {

public static void Main (string[] args) {
Create a date formatter that can parse dates of
The form mm-dd-yyyy.
SimpleDateFormat Bartdateformat =
New SimpleDateFormat ("mm-dd-yyyy");

Create A string containing a text date to be parsed.
String datestringtoparse = "9-29-2001";

try {
Parse the text version of the date.
We have to perform the parse method in a
Try-catch construct in case Datestringtoparse
Does not contain a date in the format we are expecting.
Date date = Bartdateformat.parse (Datestringtoparse);

Now send the parsed date as a Long value
to the system output.
System.out.println (Date.gettime ());
}
catch (Exception ex) {
System.out.println (Ex.getmessage ());
}
}
}

V. Using the standard date formatting process

Now that we can generate and parse custom date formats, let's take a look at how to use the built-in formatting process. Method Dateformat.getdatetimeinstance () allows us to obtain the standard date formatting process in several different ways. In the following example, we obtained four built-in date formatting processes. They include a short, medium, long, and full date format.

Import Java.text.DateFormat;
Import Java.util.Date;

public class DateExample4 {

public static void Main (string[] args) {
Date date = new Date ();

DateFormat Shortdateformat =
Dateformat.getdatetimeinstance (
Dateformat.short,
Dateformat.short);

DateFormat Mediumdateformat =
Dateformat.getdatetimeinstance (
Dateformat.medium,
Dateformat.medium);

DateFormat Longdateformat =
Dateformat.getdatetimeinstance (
Dateformat.long,
Dateformat.long);

DateFormat Fulldateformat =
Dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full);

System.out.println (Shortdateformat.format (date));
System.out.println (Mediumdateformat.format (date));
System.out.println (Longdateformat.format (date));
System.out.println (Fulldateformat.format (date));
}
}

Note that we have passed two values in each call to Getdatetimeinstance. The first parameter is a date style, and the second parameter is the time style. They are all basic data type int (integer type). For readability, we used the constants provided by the DateFormat class: Short, MEDIUM, LONG, and full. To know more methods and options for getting the time and date formatting process, see the explanation on the Sun Company web site.

When running our example program, it will output the following content to the standard output device:
9/29/01 8:44 PM
SEP, 2001 8:44:45 PM
September, 2001 8:44:45 PM EDT
Saturday, September, 2001 8:44:45 PM EDT

Of course, do not have to insert the time outside, because in the database, it can be automatically inserted, such as: MSSQL inside, with

GETDATE () to insert the current time, and at insert, you can do it. But sometimes you can't avoid it, you have to insert it manually.

Time to update the database.

Vi. Java.util.Calendar Format Time

Calendar cal = new GregorianCalendar ();
int year = Cal.get (calendar.year);
int month = Cal.get (calendar.month) +1;
int day = Cal.get (calendar.day_of_month);
int dayOfWeek = Cal.get (Calendar.day_of_week);
String week = "";
Switch (DayOfWeek) {
Case 1:
Week = "Sunday"; Break
Case 2:
Week = "Monday"; Break
Case 3:
Week = "Tuesday"; Break
Case 4:
Week = "Wednesday"; Break
Case 5:
Week = "Thursday"; Break
Case 6:
Week = "Friday"; Break
Default
Week = "Saturday"; Break

int hour = Cal.get (Calendar.hour_of_day); 24-hour system
int hour = Cal.get (Calendar.hour); 12-hour system
int minute = Cal.get (Calendar.minute);
int second = Cal.get (Calendar.second);
String h,m,s;
if (hour<10) H = "0" +hour; else H = hour+ "";
if (minute<10) m = "0" +minute; else m = minute+ "";
if (second<10) s = "0" +second; else s = second+ "";

The output in the JSP is:

Today is: Month Day::

Result: Today is: April 14, 2006 Friday 05:35:26

2. Insert the time in the database

PreparedStatement PS = con.preparestatement ("INSERT into TableName (daddtime) VALUES (?)");
There are three ways of doing this:
1) ps.setdate (1,new java.sql.Date (System.currenttimemillis ()));
2) Ps.settime (2,new java.sql.Time (System.currenttimemillis ()));
3) Ps.settimestamp (3,new Java.sql.Timestamp (System.currenttimemillis ()));
The first type is only inserted in the month of 0000-00-00

The implementation of common formats:

SimpleDateFormat formatterhwy=new SimpleDateFormat ("Yyyy-mm-dd");
Java.util.Date syscurrentime=new java.util.Date ();
String Currentsysdate=formatterhwy.format (syscurrentime);

SimpleDateFormat myformatter=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Java.util.Date mycurrentime=new java.util.Date ();
String Mycurrentdate=myformatter.format (mycurrentime);

SimpleDateFormat formatterms=new SimpleDateFormat ("Yyyy-mm-dd hh:mm");
Java.util.Date currentimems=new java.util.Date ();
String Currentdatems=formatterms.format (Currentimems);

SimpleDateFormat formatterms1=new SimpleDateFormat ("YyyyMMdd");
Java.util.Date currentimems1=new java.util.Date ();
String Currentdatems1=formatterms1.format (CURRENTIMEMS1);

Long Today=system.currenttimemillis ();
Java.util.Date todaytime=new java.util.Date (today);
SimpleDateFormat formattertoday=new SimpleDateFormat ("Yyyy-mm-dd");//Today's date
String Todaydate=formattertoday.format (todaytime);

Long yestoday=today-86400000;
Java.util.Date yestodaytime=new java.util.Date (yestoday);
SimpleDateFormat formatteryestoday=new SimpleDateFormat ("Yyyy-mm-dd");//Yesterday's date
String Yestodaydate=formatteryestoday.format (yestodaytime);

Long lasthour=today-3600000;
Java.util.Date lasthourtime=new java.util.Date (lasthour);
SimpleDateFormat formattershour=new SimpleDateFormat ("Yyyy-mm-dd hh:00:00");//The one-hour start time of the day
SimpleDateFormat formatterehour=new SimpleDateFormat ("Yyyy-mm-dd hh:59:59");//one-hour end of the day
String Lastshourdate=formattershour.format (lasthourtime);
String Lastehourdate=formatterehour.format (lasthourtime);

Long Fristday=system.currenttimemillis (); First day of the month
Java.util.Date fristdaytime=new java.util.Date (fristday);
SimpleDateFormat formatterfristday=new SimpleDateFormat ("Yyyy-mm-dd");//Yesterday's date
String Fristdate=formatterfristday.format (fristdaytime);

if (Fristdate.substring (Fristdate.length ()-2). Equals ("01")) {
Is
}

Example:

Calendar ca=calendar.getinstance ();
Java.util.Date nowdate = new Java.util.Date ();//Get current time
Ca.settime (nowdate);
Ca.set (Calendar.day_of_year, Ca.get (calendar.day_of_year)-1);//You want the day before, minus a few days.
Date now = new Date (Ca.gettimeinmillis ());//This is the time of the first n days

public static String Getweeksande (int year,int weeki) {//Return week start date and end date separated by commas
String sdate= "";
String edate= "";
Calendar cal = Calendar.getinstance ();
Cal.clear ();
Cal.set (Calendar.year, year);
Cal.set (Calendar.week_of_year, Weeki);
Cal.add (calendar.day_of_year, 1);
Sdate=cal.get (calendar.year) + "-" + (Cal.get (calendar.month) +1) + "-" +cal.get (calendar.date);

Cal.clear ();
Cal.set (Calendar.year, year);
Cal.set (Calendar.week_of_year, Weeki);
Cal.add (calendar.week_of_year, 1);
Edate=cal.get (calendar.year) + "-" + (Cal.get (calendar.month) +1) + "-" +cal.get (calendar.date);

Return sdate+ "," +edate;
}

Import java.util.*;

public class Showdate {

public static void Main (string[] args) {

Calendar calendar = new GregorianCalendar ();
Date Trialtime = new Date ();
Calendar.settime (Trialtime);

Print out a bunch of interesting things

System.out.println ("ERA:" + calendar.get (Calendar.era));
System.out.println ("Year:" + Calendar.get (calendar.year));
System.out.println ("MONTH:" + calendar.get (calendar.month));
System.out.println ("Week_of_year:"
+ calendar.get (calendar.week_of_year));
System.out.println ("Week_of_month:"
+ calendar.get (calendar.week_of_month));
System.out.println ("DATE:" + calendar.get (calendar.date));
System.out.println ("Day_of_month:"
+ calendar.get (calendar.day_of_month));
System.out
. println ("day_of_year:" + calendar.get (calendar.day_of_year));
System.out
. println ("Day_of_week:" + calendar.get (Calendar.day_of_week));
System.out.println ("Day_of_week_in_month:"
+ calendar.get (calendar.day_of_week_in_month));
System.out.println ("am_pm:" + calendar.get (calendar.am_pm));
System.out.println ("HOUR:" + calendar.get (calendar.hour));
System.out
. println ("Hour_of_day:" + calendar.get (calendar.hour_of_day));
System.out.println ("MINUTE:" + calendar.get (Calendar.minute));
System.out.println ("SECOND:" + calendar.get (Calendar.second));
System.out
. println ("Millisecond:" + calendar.get (Calendar.millisecond));
System.out.println ("Zone_offset:"
+ (Calendar.get (calendar.zone_offset)/(60 * 60 * 1000)));
System.out.println ("Dst_offset:"
+ (Calendar.get (calendar.dst_offset)/(60 * 60 * 1000)));
System.out.println ("Current time, with hour reset to 3");
Calendar.clear (Calendar.hour_of_day); So doesn ' t override
Calendar.set (Calendar.hour, 3);
System.out.println ("ERA:" + calendar.get (Calendar.era));
System.out.println ("Year:" + Calendar.get (calendar.year));
System.out.println ("MONTH:" + calendar.get (calendar.month));
System.out.println ("Week_of_year:"
+ calendar.get (calendar.week_of_year));
System.out.println ("Week_of_month:"
+ calendar.get (calendar.week_of_month));
System.out.println ("DATE:" + calendar.get (calendar.date));
System.out.println ("Day_of_month:"
+ calendar.get (calendar.day_of_month));
System.out
. println ("day_of_year:" + calendar.get (calendar.day_of_year));
System.out
. println ("Day_of_week:" + calendar.get (Calendar.day_of_week));
System.out.println ("Day_of_week_in_month:"
+ calendar.get (calendar.day_of_week_in_month));
System.out.println ("am_pm:" + calendar.get (calendar.am_pm));
System.out.println ("HOUR:" + calendar.get (calendar.hour));
System.out
. println ("Hour_of_day:" + calendar.get (calendar.hour_of_day));
System.out.println ("MINUTE:" + calendar.get (Calendar.minute));
System.out.println ("SECOND:" + calendar.get (Calendar.second));
System.out
. println ("Millisecond:" + calendar.get (Calendar.millisecond));
System.out.println ("Zone_offset:"
+ (Calendar.get (calendar.zone_offset)/(60 * 60 * 1000))); Inch
System.out.println ("Dst_offset:"
+ (Calendar.get (calendar.dst_offset)/(60 * 60 * 1000))); Inch
}}

How to use the date and calender classes 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.