java yyyy-mm-dd 日期格式,日历日期以yyyy-MM-dd格式在java中

How to convert calendar date to yyyy-MM-dd format.

Calendar cal = Calendar.getInstance();

cal.add(Calendar.DATE, 1);

Date date = cal.getTime();

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

String date1 = format1.format(date);

Date inActiveDate = null;

try {

inActiveDate = format1.parse(date1);

} catch (ParseException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.

解决方案

A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.

When you use something like System.out.println(date), Java uses Date.toString() to print the contents.

The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).

What you can do, is format the date.

Calendar cal = Calendar.getInstance();

cal.add(Calendar.DATE, 1);

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

System.out.println(cal.getTime());

// Output "Wed Sep 26 14:23:28 EST 2012"

String formatted = format1.format(cal.getTime());

System.out.println(formatted);

// Output "2012-09-26"

System.out.println(format1.parse(formatted));

// Output "Wed Sep 26 00:00:00 EST 2012"

These are actually the same date, represented differently.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值