lesson6.8与日期和事件有关的类

Date和DateFormat类SimpleDateFormat类

Date类表示时间,DateFormat类用来格式化解释日期和时间,是抽象类,通常使用它的子类SimpleDateFormat。

使用示例:

SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");//以类似2003-03-15的方     //式解释日期和时间

Date d = s1.parse("2003-03-15");//以s1的格式存入d,解析字符串文本生成Date

SimpleDateFormat s2 = new SimpleDateFormat("yyyy年MM月dd日");//另一种格式

System.out.println("s2.format(d)");//将给定的 Date 格式化为日期/时间字符串



Calendar类主要用于完成时期时间字段之间的操作,也是个抽象基类

常用Calendar gc = Calendar.getInstance();//获得日历

static void add(int field, int amount);//在field的字段上增加amount,field可以是Calendar.YEAR/MONTH/DAY_OF_MONTH等等。

int get(int field);//获取某字段的值,field同上

void set(int field, int amount);//将给定的日历字段设为给定值。


java.util.Timer类

一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

schedule方法会启动一个线程,执行TimerTask里的run方法,TimerTask实现Runnable接口,所以TimerTask必须覆盖run方法。

void schedule(timerTask task, long delay);//延迟delay执行task

void schedule(timerTask task, Date time);//在指定时间time执行task

void schedule(timerTask task,Date firsttime, lont period);//在制定的时间重复执行task,间隔period

注意:该方法启动的现成是前台线程,要结束有两种方法

Timer.cancel()//结束线程

TimerTask.cancel()//取消任务


习题:

1.将2003-03-15以2003年03月15号打印

2. 输出当前日期和315天以后的日期

3.五秒后启动计算器程序,并且把程序关闭

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


public class TestDate {

	public static void main(String [] args)
	{
		//计算距当前日期315天后的日期
		Calendar gc = Calendar.getInstance();
		System.out.println(gc.get(Calendar.YEAR)+"年"+gc.get(Calendar.MONTH)+"月"
				+gc.get(Calendar.DAY_OF_MONTH)+"日"+gc.get(Calendar.HOUR_OF_DAY)
				+"时"+gc.get(Calendar.MINUTE)+"分"+gc.get(Calendar.SECOND)+"秒");
		gc.add(Calendar.DAY_OF_YEAR, 315);
		System.out.println(gc.get(Calendar.YEAR)+"年"+gc.get(Calendar.MONTH)+"月"
				+gc.get(Calendar.DAY_OF_MONTH)+"日"+gc.get(Calendar.HOUR_OF_DAY)
				+"时"+gc.get(Calendar.MINUTE)+"分"+gc.get(Calendar.SECOND)+"秒");
		
		
		//将2003-03-15存入Date以另一种形式打印
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat s1 = new SimpleDateFormat("yyyy年MM月dd日");
		try{
			Date d = s.parse("2003-03-15");
			System.out.println(s1.format(d));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		
		//程序启动五秒后启动计算器程序
		Timer t = new Timer();
		MyTask mt = new MyTask(t);
		t.schedule(mt, 5000);//默认是前台线程,打开了计算器程序不会执行完毕
		
		//结束程序的方法
		//Timer.cancel()//结束线程
		//TimerTask.cancel()//取消任务
	}
}
class MyTask extends TimerTask
{
	private Timer t = null;
	MyTask(Timer t)
	{
		this.t =t; 
	}
	public void run()
	{
		try{Runtime.getRuntime().exec("calc.exe");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		t.cancel();
	}
}














 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值