Java中如何将日期转换为字符串

时间:2020-02-23 14:34:16  来源:igfitidea点击:

在本教程中,我们将看到如何将日期转换为Java中的字符串。
它的内容大多是在生成任何PDF或者Excel报告时以不同的字符串格式显示日期的实用程序。
我们还可以检查如何将字符串转换为日期

Java程序:

package org.igi.theitroad;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
/**
 * SimpleDateFormat example: Convert from a Date to a formatted String
 *
 
 */
public class SimpleDateFormatExample
{
  public static void main(String[] args)
  {
    // get today's date
    Date todayDate = Calendar.getInstance().getTime();
 
    // we need to create format object here by specifying desired string format
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
 
    //create a new String using the date format we want
    String dateInStringFormat = formatter.format(todayDate);
     
    // this prints date in required format 
    System.out.println("Date in format yyyy-MM-dd-hh.mm.ss = " + dateInStringFormat);
    
    //More examples:
    
    //Example 2
    formatter = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format dd/MM/yyyy hh.mm.ss = " + dateInStringFormat);
    
    //Example 3
    formatter = new SimpleDateFormat("yyyyMMdd");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format yyyyMMdd = " + dateInStringFormat);
    
    //Example 4
    formatter = new SimpleDateFormat("E, MMM dd yyyy");
    dateInStringFormat = formatter.format(todayDate);
    System.out.println("Date in format E, MMM dd yyyy = " + dateInStringFormat);
    
  }
}

运行上面的程序时,我们将获取以下输出:

Date in format yyyy-MM-dd-hh.mm.ss = 2015-01-26-02.03.02
Date in format dd/MM/yyyy hh.mm.ss = 26/01/2015 02.03.02
Date in format yyyyMMdd = 20150126
Date in format E, MMM dd yyyy = Tue, Jan 26 2015