如何获取格式化日期?

时间:2014-09-29 10:16:40

标签: java mysql date javabeans

我有一个bean,因为我有一个日期类型的属性。

private Date insurance_date;
public Date getInsurance_date() {
    return insurance_date;
}
public void setInsurance_date(Date insurance_date) {
    this.insurance_date = insurance_date;
}

但get方法给我们一个时间日期,所以我写了一个格式化的方法,

public String getFormatedDoI() {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        String stirngDate = null ;

        if(insurance_date != null)
            stirngDate = df.format((insurance_date));               
        return stirngDate;
    }

但问题是我在db中的日期为2014-05-21,当我使用getFormatedDoI()方法打印21-00-2014时。实际上,对于所有日期而不是月份,它显示0。我怎样才能得到确切的格式化日期。我正在使用的数据库是mysql。来自MYSQL数据库的日期。

4 个答案:

答案 0 :(得分:2)

小mm是分钟,大写MM是月份号码,如果你想获得月份名称你可以使用MMM,在你的情况下使用“dd-MM-yyy”而不是'dd-mm-yyyy'。

public String getFormatedDoI() {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        String stirngDate = null ;

        if(insurance_date != null)
            stirngDate = df.format((insurance_date));

        return stirngDate;
    }

应该解决你的问题:)

答案 1 :(得分:1)

mm takes minute

如果您想要月份,请使用MM

所以而不是DateFormat df = new SimpleDateFormat("dd-mm-yyyy");

使用:DateFormat df = new SimpleDateFormat("dd-MM-yyyy");

请参阅有关日期格式的this文档。

答案 2 :(得分:1)

尝试

DateFormat df = new SimpleDateFormat("dd-MM-yyyy");  

而不是

DateFormat df = new SimpleDateFormat("dd-mm-yyyy");

它应该解决

答案 3 :(得分:0)

使用" dd-MM-yyyy"而不是" dd-mm-yyyy"。模式" mm"代表分钟而不是月份。

相关问题