【Joda-Time 與 JSR310 】(1)Date 與 Calendar 怎麼了?
【Joda-Time 與 JSR310 】系列,將會以我在 2013 Java TWO 分享的 Joda-Time & JSR 310 內容為基礎,這也是我對 技術簡報三部曲 的實現。 日期與時間處理 API,在各種語言中,可能都只是個不起眼的 API,如果你沒有較複雜的時間處理需求,可能只是利用日期與時間處理 API 取得系統時間,簡單地做些顯示罷了,然而如果真的要認真看待日期與時間,其複雜程度可能會遠超過你的想像,天文、地理、歷史、政治、文化等因素,都會影響到你對時間的處理。 在 Java 的世界中,處理日期最基本的 API 就是 import java.util.*; import java.text.*; public class Main { public static void main(String[] args) throws Exception { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date birthDate = dateFormat.parse(args[0]); Date nowDate = new Date(); long lifeMillis = nowDate.getTime() - birthDate.getTime(); System.out.printf("你今年的歲數為:%d%n", lifeMillis / (365 * 24 * 60 * 60 * 1000)); } } 看來沒什麼問題?從命令列引數取得日期格式字串並剖析為 System.out.printf("你今年的歲數為:%d%n", lifeMillis / (365 * 24 * 60 * 60 * 1000L)); 其實在建構 Date date = new Date(13, 8, 2); DateFormat dateFormat = DateFormat.getDateInstance(); System.out.printf("Taiwan Java Developer Day is %s.%n", dateFormat.format(date)); 如果真要用 應該會有人告訴你,如果你要設置日期,應該使用 Calendar calendar = Calendar.getInstance(); calendar.set(2013, 8, 2); DateFormat dateFormat = DateFormat.getDateInstance(); System.out.printf("Taiwan Java Developer Day is %s.%n", dateFormat.format(calendar.getTime())); 如果你想表達的還是 calendar.set(2013, Calendar.AUGUST, 2);
public static void main(String[] args) { Calendar birth = Calendar.getInstance(); birth.set(1975, Calendar.MAY, 26); Calendar now = Calendar.getInstance(); System.out.println(daysBetween(birth, now)); System.out.println(daysBetween(birth, now)); // 顯示 0? } public static long daysBetween(Calendar begin, Calendar end) { long daysBetween = 0; while(begin.before(end)) { begin.add(Calendar.DAY_OF_MONTH, 1); daysBetween++; } return daysBetween; }
public static long daysBetween(Calendar begin, Calendar end) { Calendar calendar = (Calendar) begin.clone(); // 複製 long daysBetween = 0; while(calendar.before(end)) { calendar.add(Calendar.DAY_OF_MONTH, 1); daysBetween++; } return daysBetween; } 陷阱還蠻多的 … 實際要探討下去,其實問題會更多,總之 … 雖然叫作 總之,在 JDK 1.1 之前,
後來,從 JDK 1.1 開始,將特定的瞬時剖析為年、月、日、時、分、秒等的方法都被廢棄了,看來
至於 /* * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ 有些人可能知道, 實際上,無論你是使用 |