学习Java中的日期和时间处理及Java日历小程序的编写
Java 在 java.util 包中提供了 Date 类,这个类封装了当前的日期和时间。 Date 类支持两种构造函数。第一个构造函数初始化对象的当前日期和时间。 Date( ) Date(long millisec) 一旦有一个可用的日期对象,可以调用以下任何一种支持的方法使用时间:
获取当前日期和时间 在 Java 中容易得到当前的日期和时间。可以使用一个简单的 Date 对象的 toString() 方法,如下所示打印当前日期和时间: import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); } } 这将产生以下结果: Mon May 04 09:51:52 CDT 2009 日期比较
使用 SimpleDateFormat 格式化日期 SimpleDateFormat 是一个具体的类,以本地方式用于格式化和转换日期。SimpleDateFormat 允许选择用户定义的模式为日期时间格式。例如: 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)); } } 这将产生以下结果: Current Date: Sun 2004.07.18 at 04:14:09 PM PDT 简单的 DateFormat 格式代码
用 printf 格式化日期 日期和时间格式用 printf 方法可以非常轻松地做到。可以使用两个字母的格式,从 t 开始并在下面给出的表格中的其中一个字母结束。例如: import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() String str = String.format("Current Date/Time : %tc",date ); System.out.printf(str); } } 这将产生以下结果: Current Date/Time : Sat Dec 15 16:37:57 MST 2012 如果提供日期多次格式化是一种不好的做法。一个格式字符串可以指示要格式化的参数的索引。 import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.printf("%1$s %2$tB %2$td,%2$tY","Due date:",date); } } 这将产生以下结果: Due date: February 09,2004 或者,也可以使用 < 标志。则表示相同的参数,根据前述格式规范,应再次使用。例如: import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display formatted date System.out.printf("%s %tB %<te,%<tY",2004 日期和时间转换字符
有相关的日期和时间等有用的类。欲了解更多详细信息,可以参考 Java 标准文档。 字符串转换日期 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); } } } 上述程序的运行示例将产生以下结果: $ 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 休眠一段时间 import java.util.*; public class SleepDemo { public static void main(String args[]) { try { System.out.println(new Date( ) + "n"); Thread.sleep(5*60*10); System.out.println(new Date( ) + "n"); } catch (Exception e) { System.out.println("Got an exception!"); } } } 这将产生以下结果: Sun May 03 18:04:41 GMT 2009 Sun May 03 18:04:51 GMT 2009 测量执行时间 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!"); } } } 这将产生以下结果: Sun May 03 18:16:51 GMT 2009 Sun May 03 18:16:57 GMT 2009 Difference is : 5993 GregorianCalendar 类 Calendar 的 getInstance() 方法返回与当前日期和时间默认语言环境和时区初始化的一个 GregorianCalendar。 GregorianCalendar 中定义了两个字段:AD 和 BC。这些代表在公历中定义的两个时代。 也有几个构造函数的 GregorianCalendar 对象:
这里是由 GregorianCalendar 类提供的一些有用的方法的列表:
示例 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; // Create a Gregorian calendar initialized // with the current date and time in the // default locale and timezone. GregorianCalendar gcalendar = new GregorianCalendar(); // Display current time and date information. 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)); // Test if the current year is a leap year if(gcalendar.isLeapYear(year)) { System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year"); } } } 这将产生以下结果: Date: Apr 22 2009 Time: 11:25:27 The current year is not a leap year 日历小程序 下面我们来看一个日历小程序。这里用传统的MVC结构,设计3个类:CalendarViewer、CalendarControlller、CalendarModel。 public class CalendarViewer extends JWindow implements ActionListener { JPanel calendarYmPanel = null; JButton leftButton = new JButton("<<"); JButton rightButton = new JButton(">>"); Label yearLabel = new Label(); Label monthLabel = new Label(); Label passedDaysLabel = new Label(); JPanel calendarWdPanel = null;// 是caledar_week和calendar_days的总包容体 JPanel calendarWeekPanel = null;// 针对周列的布局 JPanel calendarDaysPanel = null;// 针对日期列的布局 JPanel calendarExitPanel = null; JButton quitButton = new JButton("关闭"); Border emptyBorder = BorderFactory.createEmptyBorder(); CalendarController cController = new CalendarController(); public CalendarViewer() { super(); buildUI(); } public void buildUI() { buildTopPanel(); buildCenterPanel(); buildBottomPanel(); setLayout(new BorderLayout()); 。。。。。。 } private void buildTopPanel() {。。。。。。} private void buildCenterPanel() {。。。。。。} private void buildBottomPanel() {。。。。。。} public JPanel updateDaysPanel() {。。。。。。} public void updatePassedDaysLabel() {。。。。。。} public void actionPerformed(ActionEvent e) {。。。。。。} public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new CalendarViewer(); } }); } } UI构造主要分3块,对应图上中下3个panel。
事件监听的处理由下面方法完成。
基于事件的UI更新由以下两个方法完成。 updateDaysPanel(); updatePassedDaysLabel(); CalendarController.java主要处理具体的业务逻辑,而所使用的一些与具体应用无关的日历算法逻辑则交给CalendarModel.java。 CalendarModel.java public class CalendarModel { private int daytab[][] = { { 0,31,28,30,31 },{ 0,29,31 } }; public boolean isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } public int dayOfYear(int day,int year) { int leap = isLeapYear(year) ? 1 : 0; for (int i = 1; i < month; i++) day += daytab[leap][i]; return day; } public int daysOfMonth(int month,int year) { int leap = isLeapYear(year) ? 1 : 0; return daytab[leap][month]; } public int dayOfWeek(int day,int year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } return (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7 + 1; } } 建立一个二维数组,分别表示闰年与非闰年的每月天数。主要方法有:
基姆拉尔森计算公式
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |