Java日期时间

来源:互联网 发布:打谱软件overture下载 编辑:程序博客网 时间:2024/05/19 03:43

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

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

描述

java.util.Date
这个类是表示日期和时间。在这个类中的大多数方法已经过时了
java.util.concurrent.TimeUnit
TIMEUNIT是用于说明日期和时间单元的枚举
java.sql.Date
这个类表示日期。切断所有的时间信息。这个日期类在JDBC中使用居多
java.sql.TimeTime: 类描述的时间(小时分秒,毫秒),并且不包含日月年的信息。这个类是经常在 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日到当前时刻的日期以毫秒为单位的时间量。

System.currentTimeMillis()通常用于测量的时间量,在开始工作之前调用,以及在工作完成后调用这个方法。

  • 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);    }}
运行示例如下:

3- TimeUnit

TimeUnit是枚举类型,它是 Java5 中才开始被引的。它有一些方法来转换时间单位,且在一些情况下真的很有用。
// Minuteint 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 microsecondspublic long toMicros(long d);// Convert to milisecondspublic long toMillis(long d);// Convert to secondspublic long toSeconds(long d);// Convert to minutespublic long toMinutes(long d);// Convert to hourspublic long toHours(long d);// Convert to dayspublic long toDays(long d) ;// Convert to unit specifiedpublic 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);    }    }
运行示例结果如下:

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);

  • 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);    }    }
运行示例如下:

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

java.sql 中有3个相关的日期和时间类:
  • java.sql.Date
  • java.sql.Time
  • java.sql.Timestamp

具体做法是:
  • 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类:

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* <code>Calendar</code> 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 <code>Calendar</code> 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 <code>Calendar</code> 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 <code>Calendar</code> 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 - 31get(Calendar.DATE)1 - 31get(Calendar.HOUR_OF_DAY)0 - 23get(Calendar.MINUTE)0 - 59get(Calendar.SECOND)0 - 59get(Calendar.MILLISECOND)0 - 999get(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 - 366get(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);    }}
运行实例:

日历的一些其他方法:
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);    }}
运行示例:

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);    }}
运行示例:

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);   }}
运行示例:

8.1- 自定义日期时间格式

自定义日期格式,让我们看看格式示例和返回结果的一些例子。
模式输出dd.MM.yy30.06.09yyyy.MM.dd G 'at' hh:mm:ss z2009.06.30 AD at 08:29:36 PDTEEE, MMM d, ''yyTue, Jun 30, '09h:mm a8:29 PMH:mm8:29H:mm:ss:SSS8:28:36:249K:mm a,z8:29 AM,PDTyyyy.MMMMM.dd GGG hh:mm aaa2009.June.30 AD 08:29 AM
日期格式模式语法
符号含意呈现示例Gera designatorTextADyyearNumber2009Mmonth in yearText & NumberJuly & 07dday in monthNumber10hhour in am/pm (1-12)Number12Hhour in day (0-23)Number0mminute in hourNumber30ssecond in minuteNumber55SmillisecondNumber978Eday in weekTextTuesdayDday in yearNumber189Fday of week in monthNumber2 (2nd Wed in July)wweek in yearNumber27Wweek in monthNumber2aam/pm markerTextPMkhour in day (1-24)Number24Khour in am/pm (0-11)Number0ztime zoneTextPacific Standard Time'escape for textDelimiter(none)'single quoteLiteral'
可以看到更多在:
  • http://java.sun.com/docs/books/tutorial/i18n/format/dateintro.html

0 0
原创粉丝点击