将一种日期格式更改为另一种

时间:2012-06-26 14:46:59

标签: java date format datetime-format

我以下列格式(Date而不是String)获取日期:

Tue Jun 26 07:00:00 EDT 2012

我想将日期格式更改为(日期):

6/26/2012 10:19:15 AM 

以便在数据库中更新相同内容。我尝试了以下代码:

Date dte;
Date dte1;(Tue Jun 26 07:00:00 EDT 2012)
SimpleDateFormat formatter = new SimpleDateFormat("m/dd/yyyy hh:mm:ss a");
String formattedDate = formatter.format(dte1);
dte  = formatter.parse(formattedDate);
SystemUtils.trace("test", " date>>>" + dte); 

正在产生以下回应:

Thu Jan 26 07:00:00 EST 2012

任何人都可以分享这段代码来做同样的事情。

4 个答案:

答案 0 :(得分:5)

您不必格式化日期以将其插入数据库中。如果使用JDBC,请使用预准备语句。

要回答您的问题,m不能同时代表分钟M表示月份。 m表示分钟

答案 1 :(得分:4)

此结果所需的代码输出:

Date dte = new Date();//or something else
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
String formattedDate = formatter.format(dte);
System.out.println(formattedDate);

答案 2 :(得分:0)

试试这个,以下代码将满足您的需求。

public class DateWala {

    public static void main(String[] args){

    System.out.println(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").format(new Date()));

   }

 }

答案 3 :(得分:0)

你可以使用这个微小的功能

// send your time
private String convertTime(String dateTime) {
//source format will go there
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    Date date = null;
    try {
        date = sdfSource.parse(dateTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    //destination format will go there
    SimpleDateFormat sdfDestination = new SimpleDateFormat("dd-MM-yyyy HH:mm");

    return sdfDestination.format(date);
}