📜  在Java中将公历更改为 SimpleDateFormat

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

在Java中将公历更改为 SimpleDateFormat

给定 GregorianCalendar 格式的日期,将其更改为 SimpleDateFormat。
例子:

Input: Sat Apr 28 13:36:37 UTC 2018
Output: 28-Apr-2018

Input: Wed Apr 03 20:49:45 IST 2019
Output: 03-Apr-2019

方法:

  1. 获取要转换的公历日期。
  2. 创建一个 SimpleDateFormat 对象,用于存储转换后的日期
  3. 现在使用 format() 方法将公历日期更改为 SimpleDateFormat。
  4. 此格式方法将公历日期的唯一日期部分作为参数。因此,使用 getTime() 方法,这个所需的日期被传递给 format() 方法。

下面是上述方法的实现:
例子:

Java
// Java program to convert
// GregorianCalendar to SimpleDateFormat
 
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
 
public class GregorianCalendarToCalendar {
 
    public static void convert(
        GregorianCalendar gregorianCalendarDate)
    {
        // Creating an object of SimpleDateFormat
        SimpleDateFormat formattedDate
            = new SimpleDateFormat("dd-MMM-yyyy");
 
        // Use format() method to change the format
        // Using getTime() method,
        // this required date is passed
        // to format() method
        String dateFormatted
            = formattedDate.format(
                gregorianCalendarDate.getTime());
 
        // Displaying gregorian date ia SimpleDateFormat
        System.out.print("SimpleDateFormat: "
                         + dateFormatted);
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Get the Gregorian Date to be converted.
        GregorianCalendar gcal = new GregorianCalendar();
        gcal.set(GregorianCalendar.YEAR, 2019);
 
        // In gregorian calendar month is started from 0
        // so for april month will be 03 not 04
        gcal.set(GregorianCalendar.MONTH, 03);
 
        gcal.set(GregorianCalendar.DATE, 03);
 
        // Displaying Current Date
        // using GregorianCalendar Class
        System.out.println("Gregorian date: "
                           + gcal.getTime());
 
        // Function to convert this to SimpleDateFormat
        convert(gcal);
    }
}


输出:
Gregorian date: Wed Apr 03 05:21:17 UTC 2019
SimpleDateFormat: 03-Apr-2019