在 toString 方法中表示公历

representing gregorian Calendar in a toString method

所以我有两个 classes,一个带有 toString 方法,我需要它打印的字段之一作为日期和时间,但我很难做到。这是我的电子邮件 class(基本字段、构造函数、getter 和 setter:

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Comparator;
import java.util.Date;

public class Email {

private String to;
private String cc;
private String bcc;
private String subject;
private String body;
private GregorianCalendar timestamp;    //time that email was created



public Email(String to, String cc, String bcc, String subject, String body) {
    super();
    this.to = to;
    this.cc = cc;
    this.bcc = bcc;
    this.subject = subject;
    this.body = body;
    timestamp  = (GregorianCalendar) new GregorianCalendar().getInstance();


}
public String getTo() {
    return to;
}
public void setTo(String to) {
    this.to = to;
}
public String getCc() {
    return cc;
}
public void setCc(String cc) {
    this.cc = cc;
}
public String getBcc() {
    return bcc;
}
public void setBcc(String bcc) {
    this.bcc = bcc;
}
public String getSubject() {
    return subject;
}
public void setSubject(String subject) {
    this.subject = subject;
}
public String getBody() {
    return body;
}
public void setBody(String body) {
    this.body = body;
}

public Date getTimestamp() {
    return timestamp.getTime();
}
public void setTimestamp(GregorianCalendar timestamp) {
    this.timestamp = timestamp;
}

这是我的文件夹 class,其中包含电子邮件对象。为了使查看更简单,我只采用了这种方法的一个例外:

import java.sql.Timestamp;
import java.util.*;

public class Folder implements Comparable{

private ArrayList<Email> emails; 
private String name;
private String currentSortingMethod; 

 //constructors, getters, setters and other methods omitted

 public String toString(){
     String a = "";
     int j = 1;
     for(int i = 0; i < emails.size(); i++){
         String k = Integer.toString(j);
         a += String.format("%-8s %-5s %-8s %-1s %10s", "  "+ k +"   ", "|" ,  emails.get(i).getTimestamp(), "|",  emails.get(i).getSubject()+ "  \n");
         j = Integer.parseInt(k);
         j++;
     }

             return(String.format("%-8s %-5s %-8s %-1s %10s", "Index", "|", "Time", "|", " Subject") + "\n" + "-------------------------------------\n" + a);
 }

toString 方法应打印如下内容

Index    |     Time     |    Subject
-------------------------------------
  1      |     Time     |       e  
  2      |     Time     |       d  
  3      |     Time     |       c  
  4      |     Time     |       b  
  5      |     Time     |       a  

它适用于其他字段,但我需要 "Time" 列填充创建该电子邮件对象时的时间戳。 示例:12:38PM 2012 年 4 月 8 日

非常感谢您的帮助!

我在本地 运行 并且它有效.. 见下文。你在时间戳字段中得到了什么?

Index    |     Time     |    Subject
-------------------------------------
  1      |     Fri Aug 12 18:16:59 PDT 2016 | subject  
  2      |     Fri Aug 12 18:17:00 PDT 2016 | subject