3

私がやろうとしているのは、カレンダーに日付を渡して、別のコンストラクターで使用できるように日付をフォーマットすることです。後でカレンダーが提供する機能を使ってそれを利用できるように。

public class Top {
public static void main(String[] args) {
    Something st = new Something(getCalendar(20,10,2012));       
    System.out.println(st.toString());       
    }

public static Calendar getCalendar(int day, int month, int year){
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, day);
    return cal;
    }
}

tostringメソッド。

public String toString(){
    String s = "nDate: " + DateD;
    return s;
}

日付:java.util.GregorianCalendar [time = ?, areFieldsSet = false、areAllFieldsSet = true、lenient = true

日付ではなく:2012年10月20日

4

5 に答える 5

1

と仮定するDateDCalendar、デフォルトのtoString()実装です。getTime()あなたはそれから抜け出すために電話する必要がありますdate

Calendar#toString()のJavaドキュメントから

このカレンダーの文字列表現を返します。このメソッドは、デバッグ目的でのみ使用することを意図しており、返される文字列の形式は実装によって異なる場合があります。返される文字列は空である可能性がありますが、null ではない可能性があります。

SimpleDateFormatを使用して変換できますString

于 2012-10-20T14:23:58.537 に答える
1

toString()まず、インスタンスを印刷するときにメソッドを明示的に使用する必要はありません。自動的に呼び出されます。

また、必要な文字列形式SimpleDateFormatにフォーマットするDateために使用する必要があります: -

Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String date = format.format(cal.getTime());

System.out.println(date);

出力: -

2012/10/20
于 2012-10-20T14:24:56.193 に答える
1

カレンダー インスタンスによって表される日付を文字列として出力する場合は、次のように、 を使用SimpleDateFormatterして必要な形式で日付をフォーマットする必要があります。

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
System.out.println(sdf.format(DateD.getTime());
于 2012-10-20T14:24:59.917 に答える
1

私には仕事が多すぎるように見えます。

ユーザーとしては、日付を渡して契約を明確にしたいと思います。String を Date に変換する便利なメソッドを提供します。

public class Top {

    public static final DateFormat DEFAULT_FORMAT;

    static {
        DEFAULT_FORMAT = new SimpleDateFormat("yyyy-MMM-dd");
        DEFAULT_FORMAT.setLenient(false);
    }

    public static void main(String [] args) {
    }

    public static Date convert(String dateStr) throws ParseException {
        return DEFAULT_FORMAT.parse(dateStr);
    }     

    public static String convert(Date d) {
        return DEFAULT_FORMAT.format(d);
    }   
}
于 2012-10-20T14:26:45.050 に答える
0

LocalDate

どうやら、日時のない日付のみの値が必要なようです。そのためには、LocalDateではなくクラスを使用してCalendarください。Calendarクラスは、日付と時刻のためのものでした。さらに、Calendar面倒で紛らわしく、欠陥があることが証明された後、java.time クラスに取って代わられ、レガシーになりました。

希望する年、月、日をファクトリ メソッドに渡すだけです。とは異なり、1 月から 12 月までは 1 から 12 までの番号が付けられCalendarます。

LocalDate ld = LocalDate.of( 2012 , 10 , 20 );

または、月の定数を渡します。

LocalDate ld = LocalDate.of( 2012 , Month.OCTOBER , 20 );

java.time クラスは、コンストラクターではなく静的ファクトリ メソッドを使用する傾向がありますnew

ストリングス

標準の ISO 8601 形式で文字列を生成するには、次を呼び出します。toString

String output = ld.toString() ;

2012-10-20

他の形式については、Stack Overflow で を検索してDateTimeFormatterください。例えば:

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( f );

2012/10/20

于 2016-12-04T23:38:10.950 に答える