Java 把公历改为SimpleDateFormat
给定一个公历格式的日期,将其改为SimpleDateFormat。
示例
输入: Sat Apr 28 13:36:37 UTC 2018
输出: 28-Apr-2018
输入: Wed Apr 03 20:49:45 IST 2019
输出: 03-Apr-2019
办法 。
- 获取要转换的格雷戈里日期。
- 创建一个SimpleDateFormat的对象,用来存储转换后的日期
- 现在使用format()方法将格雷戈里日期转换成SimpleDateFormat。
- 这个格式方法将只接受格雷戈里日期的日期部分作为参数。因此,使用getTime()方法,这个所需的日期被传递给format()方法。
下面是上述方法的实现:
示例:
// 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 in 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