2013-03-13 25 views
1

我想使用此代码:更改日期格式MM-DD-YYYY HH:MM

private static Date getTimeStamp() { 
    return new Timestamp(new Date().getTime()); 
} 

什么,我得到的是2013-03-13 12:46:22.011

但我需要的是,时间戳的格式应该是mm-dd-yyyy hh:mm

+0

使用的SimpleDateFormat格式化日期。 String format = MM-dd-yyyy HH:mm SimpleDateFormat dateFormatter = new SimpleDateFormat(format); 字符串\t dateString = dateFormatter.format(dateToFormat); – kumar 2013-03-13 07:29:04

回答

5

java.sql.Timestamp对象(就像java.util.Datejava.sql.Date)没有自己的格式,所以你不能“以[whatever]格式有时间戳”。

只有格式适用于将对象转换为字符串进行显示。您可以使用SimpleDateFormatTimestamp转换为字符串,并使用所需的格式。

Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 

DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm"); 
String text = dateFormat.format(timestamp); 

System.out.println(text); 
+0

:thanx回复。 我不能把事情联系起来。非常遗憾 。 我如何使用你的代码。虽然我对java很陌生 日期dateCreated = getTimeStamp(); \t私人日期getTimeStamp(){ \t \t \t \t回新的时间戳(新的Date()的getTime()); \t} – 2013-03-13 07:51:48

+1

我修改了我的示例,使其更清晰一些。您需要使用'SimpleDateFormat'对象将'Timestamp'转换为'String'。然后你可以显示该字符串,例如'System.out.println'。详细了解[使用对象和调用方法](http://docs.oracle.com/javase/tutorial/java/javaOO/),这将使其更加清晰。 – Jesper 2013-03-13 08:24:46

2

希望这有助于

String date1="2013-03-13 12:46:22.011"; 
    DateFormat userDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS"); 
    DateFormat dateFormatNeeded = new SimpleDateFormat("MM/dd/yyyy HH:mm"); 
    Date date = userDateFormat.parse(date1); 
    String finaldate = dateFormatNeeded.format(date);