使用 Date 和 SimpleDateFormat 类表示时间

不打扰是莪最后的温柔 提交于 2020-03-01 22:50:13

使用 Date 和 SimpleDateFormat 类表示时间

Date 类的使用:在这里插入图片描述
使用 Date 类的默认无参构造方法创建出的对象就代表当前时间,我们可以直接输出 Date 对象显示当前的时间,显示的结果如下:在这里插入图片描述

  1. 使用 format() 方法将日期转换为指定格式的文本在这里插入图片描述
    代码中的 “yyyy-MM-dd HH:mm:ss” 为预定义字符串, yyyy 表示四位年, MM 表示两位月份, dd 表示两位日期, HH 表示小时(使用24小时制), mm 表示分钟, ss 表示秒,这样就指定了转换的目标格式,最后调用 format() 方法将时间转换为指定的格式的字符串。

运行结果:2014-06-11 09:55:48

  1. 使用 parse() 方法将文本转换为日期
    在这里插入图片描述

代码中的 “yyyy年MM月dd日 HH:mm:ss” 指定了字符串的日期格式,调用 parse() 方法将文本转换为日期。

运行结果:
在这里插入图片描述
一定要注意哦:

1、 调用 SimpleDateFormat 对象的 parse() 方法时可能会出现转换异常,即 ParseException ,因此需要进行异常处理

2、 使用 Date 类时需要导入 java.util 包,使用 SimpleDateFormat 时需要导入 java.text 包

样例代码:

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);
	}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!