java实践操作。
一、知识点
(1)转换时间输出格式
1 2 3 |
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); Date now = new Date(); System.out.println(sdf1.format(now)); |
(2)使用 Date 和 SimpleDateFormat 类表示时间
在程序开发中,经常需要处理日期和时间的相关数据,此时我们可以使用 java.util 包中的 Date 类。
这个类最主要的作用就是获取当前时间,我们来看下 Date 类的使用:
使用 Date 类的默认无参构造方法创建出的对象就代表当前时间,我们可以直接输出 Date对象显示当前的时间,显示的结果如下:
其中,Wed代表 Wednesday (星期三),Jun代表June (六月),11 代表11号,CST代表 China Standard Time (中国标准时间,也就是北京时间,东八区)。
从上面的输出结果中,我们发现,默认的时间格式不是很友好,与我们日常看到的日期格式不太一样。如果想要按指定的格式进行显示,如2014-06-11 09:22:30,那该怎么做呢?
可以使用 SimpleDateFormat 来对日期时间进行格式化,如可以将日期转换为指定格式的文本,也可将文本转换为日期。
1.使用format()方法将日期转换为指定格式的文本
代码中的“yyyy-MM-dd HH:mm:ss”为预定义字符串, yyyy表示四位年,MM表示两位月份,dd 表示两位日期,HH表示小时(使用24小时制),mm表示分钟,ss表示秒,这样就指定了转换的目标格式,最后调用format()方法将时间转换为指定的格式的字符串。
运行结果:
1 |
2014-06-11 09:55:48 |
2.使用 parse() 方法将文本转换为日期
代码中的“yyyy年MM月dd日 HH:mm:ss”指定了字符串的日期格式,调用parse()方法将文本转换为日期。
运行结果:
(3)注意
- 调用SimpleDateFormat对象的parse()方法时可能会出现转换异常,即ParseException,因此需要进行异常处理。
- 使用Date类时需要导入java.util包,使用SimpleDateFormat时需要导入java.text包。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class HelloWorld { public static void main(String[] args) throws ParseException { // 使用format()方法将日期转换为指定格式的文本 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm"); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 创建Date对象,表示当前时间 Date now = new Date(); // 调用format()方法,将日期转换为字符串并输出 System.out.println(sdf1.format(now)); System.out.println(sdf2.format(now)); System.out.println(sdf3.format(now)); // 使用parse()方法将文本转换为日期 String d = "2014-6-1 21:05:36"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 调用parse()方法,将字符串转换为日期 Date date = sdf.parse(d); System.out.println(date); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package test集合; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class test { public static void main(String[] args) throws ParseException { Date d = new Date(); System.out.println(d); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String m = sf.format(d); System.out.println(m); String ds = "2014-6-1 21:05:36"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 调用parse()方法,将字符串转换为日期 Date date = sdf.parse(ds); System.out.println(date); } } |
二、总结
记录一下。