📜  Java中的日期 toString() 方法及示例

📅  最后修改于: 2022-05-13 01:55:30.806000             🧑  作者: Mango

Java中的日期 toString() 方法及示例

Java Date 类toString()方法将此日期对象转换为形式为“dow mon dd hh:mm:ss zzz yyy”的字符串。此方法覆盖类对象中的 toString。
句法:

public String toString()

参数:该函数不接受任何参数。

返回值: It 方法返回此日期的字符串表示形式。

异常:该函数不抛出任何异常。

下面的程序演示了上述函数:

// Java code to demonstrate
// toString() function of Date class
  
import java.util.Date;
import java.util.Calendar;
public class GfG {
    // main method
    public static void main(String[] args)
    {
  
        // creating a Calendar object
        Calendar c1 = Calendar.getInstance();
  
        // set Month
        // MONTH starts with 0 i.e. ( 0 - Jan)
        c1.set(Calendar.MONTH, 11);
  
        // set Date
        c1.set(Calendar.DATE, 05);
  
        // set Year
        c1.set(Calendar.YEAR, 1996);
  
        // creating a date object with specified time.
        Date dateOne = c1.getTime();
  
        System.out.println(dateOne.toString());
    }
}
输出:
Thu Dec 05 08:21:00 UTC 1996
// Java code to demonstrate
// toString() function of Date class
  
import java.util.Date;
import java.util.Calendar;
public class GfG {
    // main method
    public static void main(String[] args)
    {
  
        // creating a Calendar object
        Calendar c1 = Calendar.getInstance();
  
        // set Month
        // MONTH starts with 0 i.e. ( 0 - Jan)
        c1.set(Calendar.MONTH, 11);
  
        // set Date
        c1.set(Calendar.DATE, 15);
  
        // set Year
        c1.set(Calendar.YEAR, 1999);
  
        // creating a date object with specified time.
        Date dateOne = c1.getTime();
  
        System.out.println(dateOne.toString());
    }
}
输出:
Wed Dec 15 08:21:02 UTC 1999