如何创建具有特定格式的Date对象 [英] How can I create a Date object with a specific format

查看:106
本文介绍了如何创建具有特定格式的Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

Date d1 = df.parse(testDateString);
String date = df.format(d1);

输出字符串:


02/04/2014

02/04/2014

现在我需要日期 d1 以相同的方式格式化(02/04/2014)。

Now I need the Date d1 formatted in the same way ("02/04/2014").

推荐答案

想要一个永远打印你想要的格式的日期对象,你必须创建一个类 Date 的子类,并覆盖 toString 那里。

If you want a date object that will always print your desired format, you have to create an own subclass of class Date and override toString there.

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDate extends Date {
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    /*
     * additional constructors
     */

    @Override
    public String toString() {
        return dateFormat.format(this);
    }
}

现在,您可以像使用 Date 之前,您不需要每次都创建 SimpleDateFormat

Now you can create this class like you did with Date before and you don't need to create the SimpleDateFormat every time.

public static void main(String[] args) {
    MyDate date = new MyDate();
    System.out.println(date);
}

输出是 23/08/2014

这是您在问题中发布的更新代码:

This is the updated code you posted in your question:

String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

MyDate d1 = (MyDate) df.parse(testDateString);
System.out.println(d1);

请注意,您不必调用 df.format(d1) d1.toString()将以格式的字符串返回日期。

Note that you don't have to call df.format(d1) anymore. d1.toString() will return the date as the formated string.

这篇关于如何创建具有特定格式的Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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