给定一个日期,任务是编写一个Java程序将给定的日期转换为字符串。
例子:
Input: date = “2020-07-27”
Output: 2020-07-27
Input: date = “2018-02-17”
Output: 2018-02-17
方法 1:使用 DateFormat.format() 方法
方法:
- 获取要转换的日期。
- 创建SimpleDateFormat类的实例以格式化日期对象的字符串表示形式。
- 使用Calendar 对象获取日期。
- 使用format() 方法将给定日期转换为字符串。
- 打印结果。
下面是上述方法的实现:
Java
// 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));
}
}
Java
// 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));
}
}
输出:
07-27-2020
方法 2:使用 LocalDate.toString() 方法
方法:
- 从date获取LocalDate的实例。
- 使用LocalDate 类的toString() 方法将给定日期转换为字符串。
- 打印结果。
下面是上述方法的实现:
Java
// 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
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live