我们之前看过,如何在 Java中将String转换为Date。这篇文章是该文章的延续,在这里我们将学习 Java 中的Date到String转换。
Java 代码:将日期转换为字符串
在本节之后,我已经共享了Date到String转换的完整代码。以下函数将Date转换为String。在下面的函数中,我使用了格式dd/MM/yyyy,但是如果你想要任何其他格式的结果,那么你可以简单地修改SimpleDateFormat中的模式。
函数:
public String convertStringToDate(Date indate){ String dateString = null; SimpleDateFormat sdfr = new SimpleDateFormat("dd/MMM/yyyy"); /*you can also use DateFormat reference instead of SimpleDateFormat * like this: DateFormat df = new SimpleDateFormat("dd/MMM/yyyy"); */ try{ dateString = sdfr.format( indate ); }catch (Exception ex ){ System.out.println(ex); } return dateString;}完成Date到String转换的示例程序
在这个例子中,我将当前日期作为输入并转换为String。为了获得各种格式的输出字符串,我在SimpleDateFormat中指定了不同的两个模式。
import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;public class DateToStringDemo{ public static void main(String args[]) { Date todaysDate = new Date(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); DateFormat df3 = new SimpleDateFormat("dd-MMM-yyyy"); DateFormat df4 = new SimpleDateFormat("MM dd, yyyy"); DateFormat df5 = new SimpleDateFormat("E, MMM dd yyyy"); DateFormat df6 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss"); try { //format() method Formats a Date into a date/time string. String testDateString = df.format(todaysDate); System.out.println("String in dd/MM/yyyy format is: " + testDateString); String str2 = df2.format(todaysDate); System.out.println("String in dd-MM-yyyy HH:mm:ss format is: " + str2); String str3 = df3.format(todaysDate); System.out.println("String in dd-MMM-yyyy format is: " + str3); String str4 = df4.format(todaysDate); System.out.println("String in MM dd, yyyy format is: " + str4); String str5 = df5.format(todaysDate); System.out.println("String in E, MMM dd yyyy format is: " + str5); String str6 = df6.format(todaysDate); System.out.println("String in E, E, MMM dd yyyy HH:mm:ss format is: " + str6); } catch (Exception ex ){ System.out.println(ex); } }}
输出:
String in dd/MM/yyyy format is: 02/01/2014String in dd-MM-yyyy HH:mm:ss format is: 02-01-2014 22:38:35String in dd-MMM-yyyy format is: 02-Jan-2014String in MM dd, yyyy format is: 01 02, 2014String in E, MMM dd yyyy format is: Thu, Jan 02 2014String in E, E, MMM dd yyyy HH:mm:ss format is: Thu, Jan 02 2014 22:38:35
