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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11209935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:15:19  来源:igfitidea点击:

Changing one date format to another

javadateformatdatetime-format

提问by user964819

I 'm getting the date in the following format (Dateand not String):

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

Tue Jun 26 07:00:00 EDT 2012

I want to change the format of the date to (Date):

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

6/26/2012 10:19:15 AM 

so as to update the same in the data base. I tried following code:

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

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); 

is yielding the following response:

正在产生以下响应:

Thu Jan 26 07:00:00 EST 2012

Can any one please share the piece of code to do the same asap.

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

回答by JB Nizet

You shouldn't have to format dates to insert them in a database. If using JDBC, use prepared statements.

您不应该必须格式化日期才能将它们插入到数据库中。如果使用 JDBC,请使用准备好的语句。

To answer your question, though, mcan't mean minuteand monthat the same time. Mmeans month. mmeans minute.

但是,要回答您的问题,m不能同时表示分钟M表示月份。m意味着分钟

回答by ArtemStorozhuk

This code outputs needed for you result:

此代码输出您需要的结果:

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);

回答by Kumar Vivek Mitra

Try this, this below code will suit your need.

试试这个,下面的代码将满足您的需要。

public class DateWala {

    public static void main(String[] args){

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

   }

 }

回答by Milon

you can use this tiny function

你可以使用这个小功能

// 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);
}