Latest web development tutorials

Java Date Time

Date java.util package provides classes to encapsulate the current date and time. Date class provides two constructors to instantiate a Date object.

The first constructor uses the current date and time to initialize the object.

Date( )

The second constructor accepts a parameter, which is the number of milliseconds since January 1, 1970 of.

Date(long millisec)

After the Date object is created, you can call the following method.

No. Method and Description
1 boolean after (Date date)
If this method is called when the Date object after the specified date returns true, otherwise it returns false.
2 boolean before (Date date)
If this method is called when the Date object before the specified date returns true, otherwise it returns false.
3 Object clone ()
Returns a copy of this object.
4 int compareTo (Date date)
Compare this method is called when the Date object to the specified date. Return 0 when the two are equal. Call object before the specified date returns a negative number. Call object after the specified date returned a positive number.
5 int compareTo (Object obj)
If obj is Date type, the operation is equivalent to compareTo (Date). Otherwise, it throws ClassCastException.
6 boolean equals (Object date)
When you call this method and the Date object is equal to the specified date when returns true, otherwise returns false.
7 long getTime ()
It returns the number of milliseconds since January 1, 1970 00:00:00 GMT represented by this Date object.
8 int hashCode ()
Returns the hash code value for this object.
9 void setTime (long time)

Self January 1, 1970 00:00:00 GMT milliseconds later time to set the time and date.
10 String toString ()
Conversion Date String object representation, and returns the string.

Get the current date and time

Java gets the current date and time is very simple, use the Date object toString () method to print the current date and time as follows:

import java.util.Date;
  
public class DateDemo {
   public static void main(String args[]) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 使用 toString() 函数显示日期时间
       System.out.println(date.toString());
   }
}

The above examples compiled results are as follows:

Mon May 04 09:51:52 CDT 2013

Compare dates

Java uses three methods to compare the following two dates:

  • Use getTime () method to get two dates (January 1, 1970 through the number of milliseconds since), then compare the two values.
  • Use before (), after () and equals (). For example, a month earlier 12 than 18, the new Date (99, 2, 12) .before (new Date (99, 2, 18)) returns true.
  • Use compareTo () method, which is defined by the Comparable interface, Date class implements this interface.

The use SimpleDateFormat to format dates

SimpleDateFormat class is a locale-sensitive manner for formatting and parsing dates. SimpleDateFormat allows you to select any custom user format date and time to run. E.g:

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

public class DateDemo {
   public static void main(String args[]) {

      Date dNow = new Date( );
      SimpleDateFormat ft = 
      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

      System.out.println("Current Date: " + ft.format(dNow));
   }
}

The above examples compiled results are as follows:

Current Date: Sun 2004.07.18 at 04:14:09 PM PDT

Simple DateFormat format encoding

Time pattern string is used to specify the time format. In this mode, all ASCII letters are reserved as pattern letters are defined as follows:

letter description Example
G Era mark AD
y Four years 2001
M month July or 07
d Month date 10
h AM / PM (1 ~ 12) hours format 12
H The hour of the day (0 to 23) twenty two
m The number of minutes 30
s Seconds 55
S Milliseconds 234
E Day of the week Tuesday
D Day of the year 360
F The first weeks of the month of the week 2 (second Wed. in July)
w The first few weeks of the year 40
W The first weeks of the month 1
a AM / PM mark PM
k The hour of the day (1 to 24) twenty four
K AM / PM (0 ~ 11) hours format 10
z Time zone Eastern Standard Time
' Text delimiter Delimiter
" apostrophe `

Use printf format dates

printf method can be easily formatted time and date. Use two-letter format, it starts with t and in the following table at the end of a letter. E.g:

import java.util.Date;

public class DateDemo {

  public static void main(String args[]) {
     // 初始化 Date 对象
     Date date = new Date();

     // 使用toString()显示日期和时间
     String str = String.format("Current Date/Time : %tc", date );

     System.out.printf(str);
  }
}

The above examples compiled results are as follows:

Current Date/Time : Sat Dec 15 16:37:57 MST 2012

If you need to repeat the offer date, then use this method to format every part of it is a bit complicated. Thus, you can use a format string pointed to be formatted index parameter.

The index must immediately% behind, and must end with $. E.g:

import java.util.Date;
  
public class DateDemo {

   public static void main(String args[]) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 使用toString()显示日期和时间
       System.out.printf("%1$s %2$tB %2$td, %2$tY", 
                         "Due date:", date);
   }
}

The above examples compiled results are as follows:

Due date: February 09, 2004

Alternatively, you can use the <flag. It shows previously formatted parameters to be used again. E.g:

import java.util.Date;
  
public class DateDemo {

   public static void main(String args[]) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 显示格式化时间
       System.out.printf("%s %tB %<te, %<tY", 
                         "Due date:", date);
   }
}

The above examples compiled results are as follows:

Due date: February 09, 2004

The date and time conversion characters

character description example
c Complete Date and Time Mon May 04 09:51:52 CDT 2009
F ISO 8601 format date 2004-02-09
D US date format (month / day / year) 02/09/2004
T Time 24 hours 18:05:19
r 12-hour time 06:05:19 pm
R 24-hour time, does not include seconds 18:05
Y 4 Year (with a leading zero) 2004
y After two years (with a leading zero) 04
C 2 years ago (with a leading zero) 20
B Full month name February
b Month Acronym Feb
n 2 months (with a leading zero) 02
d 2 days (with a leading zero) 03
e 2 days (without the leading 0) 9
A Week full name Monday
a Short week Mon
j 3 years (with a leading zero) 069
H 2 hours (with a leading zero), 00-23 18
k 2 hours (without the leading 0), 0-23 18
I 2 hours (with a leading zero), 01-12 06
l 2 hours (without the leading 0), 1-12 6
M 2 minutes (with a leading zero) 05
S 2 seconds (with a leading zero) 19
L 3 ms (with a leading zero) 047
N 9 ns (with a leading zero) 047 million
P Capitalized on the afternoon of flag PM
p On the afternoon of lowercase logo pm
z Offset from GMT in RFC 822 Digital -0800
Z Time zone PST
s The number of seconds since 1970-01-01 00:00:00 GMT 1078884319
Q Since 1970-01-01 00:00:00 GMT cents wonderful 1078884319047

There are other useful date and time of the class. For more details, you can refer to the Java standard documentation.


Parsing a string to a time

SimpleDateFormat class has some additional methods, especially parse (), which tried to follow the given SimpleDateFormat object storage format to parse the string. E.g:

import java.util.*;
import java.text.*;
  
public class DateDemo {

   public static void main(String args[]) {
      SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); 

      String input = args.length == 0 ? "1818-11-11" : args[0]; 

      System.out.print(input + " Parses as "); 

      Date t; 

      try { 
          t = ft.parse(input); 
          System.out.println(t); 
      } catch (ParseException e) { 
          System.out.println("Unparseable using " + ft); 
      }
   }
}

The above examples compiled results are as follows:

$ java DateDemo
1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818
$ java DateDemo 2007-12-01
2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007

Java dormant (sleep)

sleep () makes the current thread into the stagnant state (blocks the current thread), so that the CPU usage, purpose is to keep the current thread alone occupy CPU resources obtained in the process to leave some time to chance another thread of execution.

You can let the program sleep one millisecond long period of time or to any of your computer's life. For example, the following program will sleep three seconds:

import java.util.*;
  
public class SleepDemo {
   public static void main(String args[]) {
      try { 
         System.out.println(new Date( ) + "\n"); 
         Thread.sleep(1000*3);   // 休眠3秒
         System.out.println(new Date( ) + "\n"); 
      } catch (Exception e) { 
          System.out.println("Got an exception!"); 
      }
   }
}

The above examples compiled results are as follows:

Thu Sep 17 10:20:30 CST 2015

Thu Sep 17 10:20:33 CST 2015

measure time

Here's an example that shows you how to measure time intervals (in milliseconds):

import java.util.*;
  
public class DiffDemo {

   public static void main(String args[]) {
      try {
         long start = System.currentTimeMillis( );
         System.out.println(new Date( ) + "\n");
         Thread.sleep(5*60*10);
         System.out.println(new Date( ) + "\n");
         long end = System.currentTimeMillis( );
         long diff = end - start;
         System.out.println("Difference is : " + diff);
      } catch (Exception e) {
         System.out.println("Got an exception!");
      }
   }
}

The above examples compiled results are as follows:

Fri Jan 08 09:48:47 CST 2016

Fri Jan 08 09:48:50 CST 2016

Difference is : 3019

Class Calendar

We are now able to format and create a date object, but how we can set and retrieve a specific part of it date data, such as hours, days, or minutes? How can we in these parts of the date plus or minus ? the answer is to use Calendar category.

Many powerful features than the Date class Calendar class, but also in the implementation than the Date class complex.

Calendar class is an abstract class that implements a specific sub-class of objects in actual use, the creation of objects is transparent to the programmer only needs to be created to use the getInstance method.

Create a Calendar object representing the current system date

Calendar c = Calendar.getInstance();//默认是当前日期

Create a Calendar object specified date

Use the Calendar class represents a particular time, you need to first create a Calendar object, and then sets the object date parameters to complete.

//创建一个代表2009年6月12日的Calendar对象
Calendar c1 = Calendar.getInstance();
c1.set(2009, 6 - 1, 12);

Calendar class object field type

Calendar type used at these constants represent different meanings, many thought this class are actually used within the jdk

constant description
Calendar.YEAR years
Calendar.MONTH month
Calendar.DATE date
Calendar.DAY_OF_MONTH Date, and identical to the above fields significance
Calendar.HOUR 12-hour hour
Calendar.HOUR_OF_DAY 24-hour hour
Calendar.MINUTE minute
Calendar.SECOND second
Calendar.DAY_OF_WEEK Day of the week

Setting Calendar class object information

Set settings

Such as:

Calendar c1 = Calendar.getInstance();

transfer:

public final void set(int year,int month,int date)
c1.set(2009, 6 - 1, 12);//把Calendar对象c1的年月日分别设这为:2009、6、12

Use the field type settings

If only set a field, such as value date can be set using the following methods:

public void set(int field,int value)

The Date object represents c1 is set to 10, all other values ​​are recalculated

c1.set(Calendar.DATE,10);

The object represents the year c1 is set to 2008, all other values ​​are recalculated

c1.set(Calendar.YEAR,2008);

Meaning of other field properties set so

Add Setting

Calendar c1 = Calendar.getInstance();

The target date plus 10 c1, c1 is also expressed as 10 days after the date, all other values ​​are recalculated

c1.add(Calendar.DATE, 10);

The target date minus 10 c1, c1 is also expressed as a date 10 days ago, all the other values ​​will be recalculated

<pre>c1.add(Calendar.DATE, -10);

add meaning other field properties so

Calendar class object to get information

Calendar c1 = Calendar.getInstance();
// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;
// 获得日期
int date = c1.get(Calendar.DATE);
// 获得小时
int hour = c1.get(Calendar.HOUR_OF_DAY);
// 获得分钟
int minute = c1.get(Calendar.MINUTE);
// 获得秒
int second = c1.get(Calendar.SECOND);
// 获得星期几(注意(这个与Date类是不同的):1代表星期日、2代表星期1、3代表星期二,以此类推)
int day = c1.get(Calendar.DAY_OF_WEEK);

GregorianCalendar class

Calendar class implements the Gregorian Calendar, GregorianCalendar Calendar class is a concrete implementation.

Calendar of getInstance () method returns a default with the current locale and time zone initialized GregorianCalendar object. GregorianCalendar defines two fields: AD and BC. These represent two calendar defined the era.

Listed below are a few GregorianCalendar object constructor:

No. Constructor and Description
1 GregorianCalendar ()
When you have the default locale default time zone Constructs a default GregorianCalendar current.
2 GregorianCalendar (int year, int month, int date)
When you have the default locale default zone Constructs a GregorianCalendar with the given date set
3 GregorianCalendar (int year, int month, int date, int hour, int minute)
Having a default locale default time zone to GregorianCalendar Constructs a given date and time settings.
4 GregorianCalendar (int year, int month, int date, int hour, int minute, int second)
Having a default locale default time zone to GregorianCalendar Constructs a given date and time settings.
5 GregorianCalendar (Locale aLocale)
When you have to set the default locale area Constructs a GregorianCalendar based current time.
6 GregorianCalendar (TimeZone zone)
In the default locale given time zone construct a GregorianCalendar based on the current time.
7 GregorianCalendar (TimeZone zone, Locale aLocale)
In a given locale given time zone Constructs a GregorianCalendar based on the current time.

Here is a list of GregorianCalendar class provides some useful methods:

No. Method and Description
1 void add (int field, int amount )
According to the calendar rules specified (signed) amount of time to the given calendar field.
2 protected void computeFields ()
UTC ms conversion time threshold value
3 protected void computeTime ()
Covering Calendar, Converts time field values ​​to UTC as milliseconds
4 boolean equals (Object obj)
Compares this GregorianCalendar to the specified Object.
5 int get (int field)
Gets the time value of the specified field
6 int getActualMaximum (int field)
Returns the current date, the maximum value of a given field
7 int getActualMinimum (int field)
Returns the current date, the minimum value of a given field
8 int getGreatestMinimum (int field)
GregorianCalendar Returns the highest minimum value for the given calendar field.
9 Date getGregorianChange ()
Get Gregorian change date.
10 int getLeastMaximum (int field)
Returns this GregorianCalendar instance of a given calendar field the lowest maximum value
11 int getMaximum (int field)
Returns GregorianCalendar instance given the maximum calendar field.
12 Date getTime ()
Get the current calendar time.
13 long getTimeInMillis ()
Get a calendar with a long integer representation of the current time
14 TimeZone getTimeZone ()
Get time zone.
15 int getMinimum (int field)
Back to the minimum value of a given field.
16 int hashCode ()
Rewrite hashCode.
17 boolean isLeapYear (int year)
Determines if the given year is a leap year.
18 void roll (int field, boolean up )
On the given time field to add or subtract a single unit of time (up / down), without changing larger fields.
19 void set (int field, int value )
With the given time value field.
20 void set (int year, int month , int date)
Set the year, the value of month and day.
twenty one void set (int year, int month , int date, int hour, int minute)
Set the year, month, day, hour, minute value.
twenty two void set (int year, int month , int date, int hour, int minute, int second)
Set the year, hour, minute, and second values ​​of the month, day.
twenty three void setGregorianChange (Date date)
Sets the GregorianCalendar change date.
twenty four void setTime (Date date)
With the given date set Calendar's current time.
25 void setTimeInMillis (long millis)
With a given number of long type is set milliseconds Calendar's current time.
26 void setTimeZone (TimeZone value)
With time zone settings to the current time zone.
27 String toString ()
Returns a string that represents the calendar.

Examples

import java.util.*;
  
public class GregorianCalendarDemo {

   public static void main(String args[]) {
      String months[] = {
      "Jan", "Feb", "Mar", "Apr",
      "May", "Jun", "Jul", "Aug",
      "Sep", "Oct", "Nov", "Dec"};
      
      int year;
      // 初始化 Gregorian 日历
      // 使用当前时间和日期
      // 默认为本地时间和时区
      GregorianCalendar gcalendar = new GregorianCalendar();
      // 显示当前时间和日期的信息
      System.out.print("Date: ");
      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
      System.out.println(year = gcalendar.get(Calendar.YEAR));
      System.out.print("Time: ");
      System.out.print(gcalendar.get(Calendar.HOUR) + ":");
      System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
      System.out.println(gcalendar.get(Calendar.SECOND));
      
      // 测试当前年份是否为闰年
      if(gcalendar.isLeapYear(year)) {
         System.out.println("当前年份是闰年");
      }
      else {
         System.out.println("当前年份不是闰年");
      }
   }
}

The above examples compiled results are as follows:

Date: Apr 22 2009
Time: 11:25:27
当前年份不是闰年