时间类型Date和字符串String的转换

1、时间格式转字符串

 public void test() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(date));
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(date));
        sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println(sdf.format(date));
    }

结果

2016-10-24
2016-10-24 21:59:06
2016102421:59:06

2、字符串转时间格式

  public void test() throws ParseException {
        String string = "2016-10-24 21:59:06";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.parse(string));
    }

结果

Mon Oct 24 21:59:06 CST 2016

在字符串转日期操作时,需要注意给定的模式必须和给定的字符串格式匹配,否则会抛出java.text.ParseException异常,例如下面这个就是错误的,字符串中并没有给出时分秒,那么SimpleDateFormat当然无法凭空解析出时分秒的值来

 public void test() throws ParseException {
        String string = "2016-10-24";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.parse(string));
    }

报错

Exception in thread "main" java.text.ParseException: Unparseable date: "2016-10-24"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at com.test.dateFormat.String2Date.main(String2Date.java:19)

不过,给定的模式比字符串少则可以

public void test() throws ParseException {
        String string = "2016-10-24 21:59:06";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.parse(string));
    }

结果

Mon Oct 24 00:00:00 CST 2016

可以看出时分秒都是0,没有被解析,这是可以的。

转载自博客园,https://www.cnblogs.com/huangminwen/p/5994846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值