从Date对象转换为Date对象

时间:2012-04-05 06:05:50

标签: java date

我有一个要求。我想将Date对象转换为格式化的Date对象。

我的意思是,

`Date d = new Date();System.out.println(d);' 

输出: Thu Apr 05 11:28:32 GMT + 05:30 2012

我希望输出像 05 / APR / 2012 。输出对象必须是Date而不是String。 如果你不清楚,我会发布更清楚的

谢谢。

3 个答案:

答案 0 :(得分:7)

不需要任何第三方API,只需使用DateFormat通过提供日期格式模式来解析/格式化日期。示例代码为:

Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
String formattedDate = df.format(date);

System.out.println(formattedDate.toUpperCase());

Demo run here.

答案 1 :(得分:1)

在回答之前,我会让其他人知道OP实际上是使用POJO来表示数据库对象,他的一个POJO包含日期类型字段。他希望日期是oracles格式,但它仍然是Date对象。 (来自OP的评论here

您只需要扩展Date类并覆盖public String toString();

public class MyDate extends Date
{
    @Override
    public String toString()
    {
        DateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
        String formattedDate = df.format(this);
        return formattedDate;
    }
}

然后,在您的POJO中,初始化Date对象:

Date databaseDate=new MyDate();
// initialize date to required value.

现在,databaseDate是一个Date对象,但它会在需要的地方提供所需的格式。

编辑:数据库与编程语言的数据类型无关。将POJO插入数据库时​​,它们的所有值都将转换为字符串。如何将对象转换为字符串在该类的toString方法中定义。

答案 2 :(得分:0)

我认为他想在System.out.println()中使用Date,所以我们可以尝试扩展Date类并覆盖toString()。

以下是代码:

import java.util.Date;


 class date extends Date {

    int mm,dd,yy;
    date()
    {

        Date d = new Date();
        System.out.println(d);
        mm=d.getMonth();
        dd=d.getDate();
        yy=d.getYear();

    }

    public String toString()
    {  Integer m2=new Integer(mm);
    Integer m3=new Integer(dd);
    Integer m4=new Integer(yy);
        String s=m2.toString() + "/"+ m3.toString() + "/" + m4.toString();

        return s;
    }


}

public class mai
{
public static void main(String... args)
{

    date d=new date();
    System.out.println(d);

}

}
相关问题