日历日期以yyyy-MM-dd格式在java中 [英] Calendar date to yyyy-MM-dd format in java

查看:722
本文介绍了日历日期以yyyy-MM-dd格式在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将日历日期转换为 yyyy-MM-dd 格式。

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();
}

这将产生 inActiveDate = Wed Sep 26 00: 00:00 IST 2012 。但我需要的是 2012-09-26 。我的目的是使用Hibernate标准将此日期与我的数据库中的另一个日期进行比较。所以我需要 yyyy-MM-dd 格式的日期对象。

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.

推荐答案

p> A Java Date 是自1970年1月1日00:00:00 GMT以来的毫秒数的容器。

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

当使用 System.out.println(date)时,Java使用 Date.toString()打印内容。

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

更改它的唯一方法是重写 Date ,并提供您自己的实现 Date.toString()。现在在你启动你的IDE和尝试这个,我不会;这只会使事情复杂化。您最好将日期格式化为要使用(或显示)的格式。

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.

这篇关于日历日期以yyyy-MM-dd格式在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆