n("30 弧度的正弦值: Math.sin(Math.toRadians(30.0))= "+d1); System.out.println("E 的对数值:Math.log(Math.E)= "+d2); System.out.println("2 的3 次方:Math.pow(2.0, 3.0)= "+d3); System.out.println("33.6F 四舍五入:Math.round(33.6F)= "+r); } } 2. 编译并运行程序,结果如图5.10 所示。
四.使用日期类
Java 提供了3 个日期类:Date、Calendar 和DateFormat。其中,Date 类主要用于创 建日期对象并获取日期, Calendar 类可获取和设置日期, DateFormat 类用来设置日期的格 式。 Java 语言规定的基准日期为1970.1.1 00:00:00 格林威治(GMT)标准时间,当前日期 是由基准日期开始所经历的毫秒数转换出来的。 1. 使用日期类的Applate 应用程序 (1)程序功能:说明3 个日期类Date、Calendar 和DateFormat 使用方式及显示的样式。 (2)编写LX5_9.java 程序文件,源代码如下。 import java.text.*; import java.util.*; import java.awt.*; import java.a
pplet.*; public class LX5_9 extends Applet { public void paint(Graphics g) { Date today; Calendar now; DateFormat f1,f2; String s1,s2; today=new Date(); // 获取系统当前日期 g.drawString("字符串格式:"+today.toString(),20,20); f1=DateFormat.getInstance(); // 以默认格式生成格式化器 s1=f1.format(today); // 将日期转换为字符串 g.drawString("系统格式:"+s1,20,40); // 生成长格式的中国日期格式化器 f1=DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA); // 生成长格式的中国时间格式化器 f2=DateFormat.getTimeInstance(DateFormat.LONG, Locale.CHINA); s1=f1.format(today); // 将日期转换为日期字符串 s2=f2.format(today); // 将日期转换为时间字符串
g.drawString("中国格式:"+s1+" "+s2,20,60); now=Calendar.getInstance(); // 获取系统时间 s1=now.get(now.HOUR)+" 时" +now.get(now.MINUTE)+" 分" +now.get(now.SECOND)+"秒"; g.drawString("调整前时间:"+s1,20,80); now.set(2004,8,15,9,9,9); today=now.getTime(); g.drawString("调整后时间:"+today.toString(),20,100); } } (3)编译程序文件。 (4)在浏览器中打开包含应用程序的页面文件,显示结果如图5.11 所示。
2. 在独立运行的应用程序中使用日期函数。 (1)程序功能:补充说明3 个日期类Date、Calendar 和DateFormat 的使用方式及显示 的样式。 (2)编写LX5_10.java 程序文件,源代码如下。 import java.util.*; import java.text.*; public class LX5_10{ public static void main (String args[]){ Date today = new Date(); //当前日期和时间 SimpleDateFormat sdf; sdf= new SimpleDateFormat("yyyy 年MM 月dd 日hh 时mm 分ss 秒 a EEEEE"); System.out.println("当前日期和时间: "+sdf.format(today)); long hms=System.currentTimeMillis(); //当前时间的毫秒数 System.out.println("当前时间的毫秒数="+hms); Date tomorrow = new Date(hms+24*60*60*1000);
System.out.println("明天是"+sdf.format(tomorrow)); Calendar now = Calendar.getInstance(); int year =now.get(Calendar