更新時間:2022-09-09 10:54:40 來源:動力節點 瀏覽6093次
給定一個日期,任務是編寫一個 Java 程序將給定的日期轉換為字符串。
輸入:日期 = “2020-07-27”
輸出: 2020-07-27
輸入:日期 = “2018-02-17”
輸出: 2018-02-17
方法:
獲取要轉換的日期。
創建SimpleDateFormat 類的實例以格式化日期對象的字符串表示形式。
使用Calendar 對象獲取日期。
使用format() 方法將給定的日期轉換為字符串。
打印結果。
下面是上述方法的實現:
// Java program to convert Date to String
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class GFG {
// Function to convert date to string
public static String
convertDateToString(String date)
{
// Converts the string
// format to date object
DateFormat df = new SimpleDateFormat(date);
// Get the date using calendar object
Date today = Calendar.getInstance()
.getTime();
// Convert the date into a
// string using format() method
String dateToString = df.format(today);
// Return the result
return (dateToString);
}
// Driver Code
public static void main(String args[])
{
// Given Date
String date = "07-27-2020";
// Convert and print the result
System.out.print(
convertDateToString(date));
}
}
輸出:
07-27-2020
方法:
從date獲取LocalDate的實例。
使用LocalDate 類的toString() 方法將給定的日期轉換為字符串。
打印結果。
下面是上述方法的實現:
// Java program to convert Date to String
import java.time.LocalDate;
class GFG {
// Function to convert date to string
public static String
convertDateToString(String date)
{
// Get an instance of LocalTime
// from date
LocalDate givenDate = LocalDate.parse(date);
// Convert the given date into a
// string using toString()method
String dateToString
= givenDate.toString();
// Return the result
return (dateToString);
}
// Driver Code
public static void main(String args[])
{
// Given Date
String date = "2020-07-27";
// Convert and print the result
System.out.print(
convertDateToString(date));
}
}
輸出:
2020-07-27
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習