【问题标题】:Why do i need DateFormat? [closed]为什么我需要日期格式? [关闭]
【发布时间】:2014-09-24 15:21:21
【问题描述】:

我是初学者,我从 Lynda 那里得到了这段代码,我不知道为什么这段代码中应该有 DateFormat:

import java.text.DateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class date {
    public static void main(String[] args){
        Date d =new Date();
        System.out.println(d);

        GregorianCalendar gc =new GregorianCalendar(2009, 1, 29 );
        gc.add(GregorianCalendar.DATE   ,1);
        Date d2 =gc.getTime();
        DateFormat df =DateFormat.getDateInstance();
        String sd =df.format(d2);
        System.out.println(sd); 
    }
}

虽然有Date d2 =gc.getTime();GregorianCalendar 获取时间,但为什么我不能只写 System.out.println(d2);

【问题讨论】:

  • System.out.println() 将打印toString() 方法中的任何内容。
  • 何不试试看?

标签: java date


【解决方案1】:

如果你直接输出Date对象,它的toString函数会被隐式调用,给你一个dow mon dd hh:mm:ss zzz yyyy格式的字符串,这可能是你想要的,也可能不是。

使用DateFormat 实现可以让您选择似乎适合您的任务的日期格式。该代码中使用的方法getDateInstance 为您提供了一个使用基于当前语言环境的格式的格式化程序。您可以通过多种其他方式获取 DateFormat 实例,具体取决于您想要执行的操作,但在当前语言环境中,这是一种合理的通用日期格式化程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多