更新時(shí)間:2022-09-09 10:54:40 來源:動(dòng)力節(jié)點(diǎn) 瀏覽6314次
給定一個(gè)日期,任務(wù)是編寫一個(gè) Java 程序?qū)⒔o定的日期轉(zhuǎn)換為字符串。
輸入:日期 = “2020-07-27”
輸出: 2020-07-27
輸入:日期 = “2018-02-17”
輸出: 2018-02-17
方法:
獲取要轉(zhuǎn)換的日期。
創(chuàng)建SimpleDateFormat 類的實(shí)例以格式化日期對(duì)象的字符串表示形式。
使用Calendar 對(duì)象獲取日期。
使用format() 方法將給定的日期轉(zhuǎn)換為字符串。
打印結(jié)果。
下面是上述方法的實(shí)現(xiàn):
// 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的實(shí)例。
使用LocalDate 類的toString() 方法將給定的日期轉(zhuǎn)換為字符串。
打印結(jié)果。
下面是上述方法的實(shí)現(xiàn):
// 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
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)