Java日期时间

1- Java中的日期,时间,日历类

Java提供有关时间和日历(Calendar)类,下面是这个类的列表:

描述

java.util.Date
这个类是表示日期和时间。在这个类中的大多数方法已经过时了
java.util.concurrent.TimeUnit
TIMEUNIT是用于说明日期和时间单元的枚举
java.sql.Date
这个类表示日期。切断所有的时间信息。这个日期类在JDBC中使用居多
java.sql.Time Time: 类描述的时间(小时分秒,毫秒),并且不包含日月年的信息。这个类是经常在 JDBC 中使用
java.sql.Timestamp
这个类表示日期和时间。此日期和时间类在JDBC中使用
java.util.Calendar
这是一个Calendar类的基类。有一些方法来做日期和时间算术运算,如添加一天或一个月到另一个日期
java.util.GregorianCalendar
一个java.util.Calendar类的子类,这在大多数西方世界的今天使用的公历表示。拥有所有 java.util.Calendar 类中的方法做,及日期和时间运算
java.util.TimeZone
Java TimeZone类是代表时区的一个类,跨时区做日历算术时是很有帮助的
java.text.SimpleDateFormat
这个类可以帮助您来解析字符串转换日期和时间格式为String

2- System.currentTimeMillis()

currentTimeMillis()是System类的静态方法。它返回从1971年1月1日到当前时刻的日期以毫秒为单位的时间量。
Java日期时间_第1张图片
System.currentTimeMillis()通常用于测量的时间量,在开始工作之前调用,以及在工作完成后调用这个方法。
Java日期时间_第2张图片
  • JobTimeDemo.java
package com.yiibai.tutorial.dt;

public class JobTimeDemo {

  
    // This is the method to sum the numbers from 1 to 100.
    private static int sum() {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }

    private static void doJob(int count) {
    
        // Invoke sum method with the number of times
        // given by the parameter.
        for (int i = 0; i < count; i++) {
            sum();
        }
    }

    public static void main(String[] args) {
        long millis1 = System.currentTimeMillis();

        doJob(10000);

        long millis2 = System.currentTimeMillis();

        long distance = millis2 - millis1;
        
        System.out.println("Distance time in milli second: "+ distance);
    }
}
运行示例如下:
Java日期时间_第3张图片

3- TimeUnit

TimeUnit是枚举类型,它是 Java5 中才开始被引的。它有一些方法来转换时间单位,且在一些情况下真的很有用。
// Minute
int minute = 5;

// Convert to milliseconds.
// This is the traditional way.
int millisecond = minute * 60 * 1000;

// With TimeUnit:
long millisecond = TimeUnit.MINUTES.toMillis(minute);
TimeUnit的一些方法
// Convert to nanoseconds.
public long toNanos(long d);

// Convert to microseconds
public long toMicros(long d);

// Convert to miliseconds
public long toMillis(long d);

// Convert to seconds
public long toSeconds(long d);

// Convert to minutes
public long toMinutes(long d);

// Convert to hours
public long toHours(long d);

// Convert to days
public long toDays(long d) ;

// Convert to unit specified
public long convert(long d, TimeUnit u);
示例:
  • TimeUnitConvertDemo.java
package com.yiibai.tutorial.timeunit;

import java.util.concurrent.TimeUnit;

public class TimeUnitConvertDemo {

    public static void main(String[] args) {

 
        long second = 125553;
  
        // Convert to minute.
        long minute = TimeUnit.MINUTES.convert(second, TimeUnit.SECONDS);
        System.out.println("Minute " + minute);
  
        // Convert to hours
        long hour = TimeUnit.HOURS.convert(second, TimeUnit.SECONDS);
        System.out.println("Hour " + hour);

        System.out.println("------");       
  
        // Convert 3 day to minute
        minute = TimeUnit.DAYS.toMinutes(3);

        System.out.println("Minute " + minute);
   
        // Convert 3 days to hours
        hour = TimeUnit.DAYS.toHours(3);

        System.out.println("Hour " + hour);
    }
    
}
运行示例结果如下:
Java日期时间_第4张图片

4- java.util.Date

Java的java.util.Date类是Java的第一个日期类之一。 现在类中大多数的方法已经被弃用,取而代之是 java.util.Calendar 类。虽然您仍然可以使用 java.util.Date 类来表示日期。
只有2个构造函数可使用:
// Create a Date object describing the current time.
Date date1 = new Date();

// Create Date object, millis - the milliseconds since January 1, 1970, 00:00:00 GMT.
long millis = .....;
Date date2 = new Date(millis);
Java日期时间_第5张图片
  • DateDemo.java
package com.yiibai.tutorial.date;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DateDemo {

    public static void main(String[] args) throws InterruptedException {

        // Create a Date object describing the current time.
        Date date1 = new Date();

        // Stop 3 seconds.
        Thread.sleep(TimeUnit.SECONDS.toMillis(3));

        // Returns the current time in milliseconds.
        // (From 01-01-1970 to now).
        long millis = System.currentTimeMillis();
        Date date2 = new Date(millis);

     
        // Compare two objects date1 and date2.
        // i < 0 means date1 < date2
        // i = 0 means date1 = date2
        // i > 0 means date1 > date2
        int i = date1.compareTo(date2);

        System.out.println("date1 compareTo date2 = " + i);

        // Tests if this date is before the specified date.
        boolean before = date1.before(date2);

        System.out.println("date1 before date2 ? " + before);

        // Tests if this date is after the specified date.
        boolean after = date1.after(date2);

        System.out.println("date1 after date2 ? " + after);
    }
    
}
运行示例如下:
Java日期时间_第6张图片

5- Date, Time, Timestamp (java.sql)

java.sql 中有3个相关的日期和时间类:
  • java.sql.Date
  • java.sql.Time
  • java.sql.Timestamp
Java日期时间_第7张图片
具体做法是:
  • java.sql.Date对应于SQL DATE,它存储年,月和天,而小时,分钟,秒和毫秒会被忽略。此外sql.Date不依赖于时区。
  • java.sql.Time对应于SQL TIME和作为应该是显而易见的,仅包含有关时,分,秒和毫秒信息。
  • java.sql.Timestamp对应于SQL TIMESTAMP,这可准确日期到纳秒(注意util.Date只支持毫秒!),并且可定制的精度。
以上类在JDBC API中使用,例如,PreparedStatement.setDate(),PreparedStatement.setDate()和PreparedStatement.setTimestamp()方法。可以从结果集进行检索。

6- java.util.Calendar

日历概况:
  • 公历:公历也叫西历和基督教的日历,是国际上最广泛使用的历法。它被命名为罗马教皇格里高利十三世,在1582推出。
    • http://en.wikipedia.org/wiki/Gregorian_calendar
  • 佛历:在一些东南亚国家如泰国,老挝,柬埔寨和斯里兰卡的常用。目前在佛教仪式中使用此日历。并没有其他国家使用该日历正式,这些国家转换为使用的公历。你可以参考在此日历上的信息:
    • http://en.wikipedia.org/wiki/Buddhist_calendar
  • 日本皇家日历:这是日本传统的日历,现在日本已切换到日历(公历),但传统的日历仍在非官方的途径中使用。
Calendar类:
Java日期时间_第8张图片
Calendar的子类:
  • GregorianCalendar
  • JapaneseImperialCalendar
  • BuddhistCalendar
Calendar是一个抽象类。这意味着,你不能从构造函数创建它。然而,有两个静态方法用来创建日历对象。
public static Calendar getInstance();

public static Calendar getInstance(TimeZone zone);

public static Calendar getInstance(Locale aLocale);

public static Calendar getInstance(TimeZone zone,Locale aLocale);
Example:
// Get the Calendar object describes the present time.
// With Locale default, your TimeZone.
Calendar c = Calendar.getInstance();
当您使用Calendar.getInstance (TimeZone, Locale),将返回为上述类之一。但大多返回公历(GregorianCalendar)。
调用 Calendar.getInstance()使用时区参数(TimeZone),根据您的计算机和默认Locale将返回日历的对象。

看一下Calendar类(JDK7)的代码:
/**
* Gets a calendar using the default time zone and locale. The
* Calendar returned is based on the current time
* in the default time zone with the default locale.
*
* @return a Calendar.
*/
public static Calendar getInstance()
{
   Calendar cal = createCalendar(TimeZone.getDefaultRef(),
                                   Locale.getDefault(Locale.Category.FORMAT));
   cal.sharedZone = true;
   return cal;
}

/**
* Gets a calendar using the specified time zone and default locale.
* The Calendar returned is based on the current time
* in the given time zone with the default locale.
*
* @param zone the time zone to use
* @return a Calendar.
*/
public static Calendar getInstance(TimeZone zone)
{
   return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
}

/**
* Gets a calendar using the default time zone and specified locale.
* The Calendar returned is based on the current time
* in the default time zone with the given locale.
*
* @param aLocale the locale for the week data
* @return a Calendar.
*/
public static Calendar getInstance(Locale aLocale)
{
   Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
   cal.sharedZone = true;
   return cal;
}

/**
* Gets a calendar with the specified time zone and locale.
* The Calendar returned is based on the current time
* in the given time zone with the given locale.
*
* @param zone the time zone to use
* @param aLocale the locale for the week data
* @return a Calendar.
*/
public static Calendar getInstance(TimeZone zone,
                                  Locale aLocale)
{
   return createCalendar(zone, aLocale);
}

private static Calendar createCalendar(TimeZone zone,
                                      Locale aLocale)
{
   Calendar cal = null;

   String caltype = aLocale.getUnicodeLocaleType("ca");
   if (caltype == null) {
       // Calendar type is not specified.
       // If the specified locale is a Thai locale,
       // returns a BuddhistCalendar instance.
       if ("th".equals(aLocale.getLanguage())
               && ("TH".equals(aLocale.getCountry()))) {
           cal = new BuddhistCalendar(zone, aLocale);
       } else {
           cal = new GregorianCalendar(zone, aLocale);
       }
   } else if (caltype.equals("japanese")) {
       cal = new JapaneseImperialCalendar(zone, aLocale);
   } else if (caltype.equals("buddhist")) {
       cal = new BuddhistCalendar(zone, aLocale);
   } else {
       // Unsupported calendar type.
       // Use Gregorian calendar as a fallback.
       cal = new GregorianCalendar(zone, aLocale);
   }

   return cal;
}
一些比较重要的方法:

get(int)方法

返回值

get(Calendar.DAY_OF_WEEK) 1 (Calendar.SUNDAY) to 7 (Calendar.SATURDAY).
get(Calendar.YEAR) 年份
get(Calendar.MONTH) 0 (Calendar.JANUARY) to 11 (Calendar.DECEMBER).
get(Calendar.DAY_OF_MONTH) 1 - 31
get(Calendar.DATE) 1 - 31
get(Calendar.HOUR_OF_DAY) 0 - 23
get(Calendar.MINUTE) 0 - 59
get(Calendar.SECOND) 0 - 59
get(Calendar.MILLISECOND) 0 - 999
get(Calendar.HOUR) 0 - 11, 能够与 Calendar.AM_PM 一起使用
get(Calendar.AM_PM) 0 (Calendar.AM) 或 1 (Calendar.PM).
get(Calendar.DAY_OF_WEEK_IN_MONTH)
1到7总是对应于DAY_OF_MONTH - DAY_OF_WEEK_IN_MONTH1;

8至14对应于DAY_OF_WEEK_IN_MONTH2依此类推。
get(Calendar.DAY_OF_YEAR) 1 - 366
get(Calendar.ZONE_OFFSET)
GMT偏移时区的值
get(Calendar.ERA)
表示AD(阳历Calendar.AD),BC(公历Calendar.BC)
  • CalendarFieldsDemo.java
package com.yiibai.tutorial.calendar;

import java.util.Calendar;

public class CalendarFieldsDemo {

    public static void main(String[] args) {
   
        // Create a calendar using the default time zone and locale.
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);

    
        // Returns value from 0 - 11
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        int millis = c.get(Calendar.MILLISECOND);

        System.out.println("Year: " + year);
        System.out.println("Month: " + (month+1));
        System.out.println("Day: " + day);
        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
        System.out.println("Minute: " + minute);
        System.out.println("Milli Second: " + millis);

    }

}
运行实例:
Java日期时间_第9张图片
日历的一些其他方法:
void set(int calendarField, int value)
void set(int year, int month, int date)
void set(int year, int month, int date, int hour, int minute, int second)

// Adds or subtracts the specified amount of time to the given calendar field,
// based on the calendar's rules.
void add(int field, int amount)

// Adds or subtracts (up/down) a single unit of time on the
// given time field without changing larger fields.
void roll(int calendarField, boolean up)

// Adds the specified (signed) amount to the specified calendar field
// without changing larger fields.
void roll(int calendarField, int amount):


// return a Date object based on this Calendar's value.
Date getTime()

void setTime(Date date)

// Returns this Calendar's time value in milliseconds.
long getTimeInMills():

void setTimeInMillis(long millis)

void setTimeZone(TimeZone value)
  • CalendarDemo.java
package com.yiibai.tutorial.calendar;

import java.util.Calendar;

public class CalendarDemo {

    public static void showCalendar(Calendar c) {
        int year = c.get(Calendar.YEAR);

      
        // Return value from 0 - 11
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        int millis = c.get(Calendar.MILLISECOND);

        System.out.println(" " + year + "-" + (month + 1) + "-" + day + " "
                + hour + ":" + minute + ":" + second + " " + millis);
    }

    public static void main(String[] args) {
  
        // Gets a calendar using the default time zone and locale
        Calendar c = Calendar.getInstance();

        System.out.println("First calendar info");
        showCalendar(c);
 
        
        // roll(..) does not change other fields.
        // Roll up one hour (boolean up = true)
        c.roll(Calendar.HOUR_OF_DAY, true);

        System.out.println("After roll 1 hour");
        showCalendar(c);
        
        // roll(..) does not change other fields.
        // Roll down one hour (boolean up = false)
        c.roll(Calendar.HOUR_OF_DAY, false);

        System.out.println("After roll -1 hour");
        showCalendar(c);

      
        // add(..) can change other fields.
        // Adding one hour (boolean up = true)
        c.add(Calendar.HOUR_OF_DAY, 1);

        System.out.println("After add 1 hour");
        showCalendar(c);

 
        // roll(..) does not change other fields.
        // Roll down 30 day (boolean up = false)
        c.roll(Calendar.DAY_OF_MONTH, -30);

        System.out.println("After roll -30 day");
        showCalendar(c);       

        
        // add(..) can change other fields.
        // Adding 30 days (boolean up = true)
        c.add(Calendar.DAY_OF_MONTH,  30);
        System.out.println("After add 30 day");
        showCalendar(c);

    }

}
运行示例:
Java日期时间_第10张图片

7- 日期和日历之间的转换

  • Date ==> Calendar
Date now = new Date();

Calendar c = Calendar.getInstance();
c.setTime(now);
  • Calendar ==> Date
Calendar c = Calendar.getInstance();

Date date = c.getTime();
  • CalendarDateConversionDemo.java
package com.yiibai.tutorial.calendar;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class CalendarDateConversionDemo {

    public static void showCalendar(Calendar c) {
        int year = c.get(Calendar.YEAR);

        
        // Returns the value from 0-11
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        int millis = c.get(Calendar.MILLISECOND);

        System.out.println(year + "-" + (month + 1) + "-" + day + " "
                + hour + ":" + minute + ":" + second + " " + millis);
    }
    
    public static void main(String[] args) {

        Calendar c = Calendar.getInstance();

        // year, month, day
        c.set(2000, 11, 24);

        Date date = c.getTime();

        System.out.println("Date " + date);

        long timeInMillis = System.currentTimeMillis();

        // subtract 24 hours
        timeInMillis -= TimeUnit.HOURS.toMillis(24);

        Date date2 = new Date(timeInMillis);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date2);

        showCalendar(c2);

    }

}
运行示例:
Java日期时间_第11张图片

8- java.text.DateFormat & java.text.SimpleDateFormat

  • Date ==> String
Date date = new Date();

DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

String dateString  = df.format(date);
  • String ==> Date
String dateString = "23/04/2005 23:11:59";

DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

Date date = df.parse(dateString);
  • DateFormatDemo.java
package com.yiibai.tutorial.dateformat;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatDemo {

   public static void main(String[] args) throws ParseException {

       final DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

       String dateString1 = "23/04/2005 23:11:59";
       System.out.println("dateString1 = " + dateString1);

       // String ==> Date
       Date date1 = df1.parse(dateString1);

       System.out.println("date1 = " + date1);

       final DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

       // Date ==> String.
       String dateString2 = df2.format(date1);

       System.out.println("dateString2 = " + dateString2);
   }
}
运行示例:
Java日期时间_第12张图片

8.1- 自定义日期时间格式

自定义日期格式,让我们看看格式示例和返回结果的一些例子。
模式 输出
dd.MM.yy 30.06.09
yyyy.MM.dd G 'at' hh:mm:ss z 2009.06.30 AD at 08:29:36 PDT
EEE, MMM d, ''yy Tue, Jun 30, '09
h:mm a 8:29 PM
H:mm 8:29
H:mm:ss:SSS 8:28:36:249
K:mm a,z 8:29 AM,PDT
yyyy.MMMMM.dd GGG hh:mm aaa 2009.June.30 AD 08:29 AM
日期格式模式语法
符号 含意 呈现 示例
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '
可以看到更多在:
  • http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html

你可能感兴趣的:(java基础,java)