我想使用此代碼:更改日期格式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
。
我想使用此代碼:更改日期格式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
。
您可以使用SimpleDateFormat http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html來實現您的目標。
例如: new SimpleDateFormat(「MM-dd-yyyy HH:mm」).format(timestamp));
java.sql.Timestamp
對象(就像java.util.Date
和java.sql.Date
)沒有自己的格式,所以你不能「以[whatever]格式有時間戳」。
只有格式適用於將對象轉換爲字符串進行顯示。您可以使用SimpleDateFormat
將Timestamp
轉換爲字符串,並使用所需的格式。
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm");
String text = dateFormat.format(timestamp);
System.out.println(text);
:thanx回覆。 我不能把事情聯繫起來。非常遺憾 。 我如何使用你的代碼。雖然我對java很陌生 日期dateCreated = getTimeStamp(); \t私人日期getTimeStamp(){ \t \t \t \t回新的時間戳(新的Date()的getTime()); \t} – 2013-03-13 07:51:48
我修改了我的示例,使其更清晰一些。您需要使用'SimpleDateFormat'對象將'Timestamp'轉換爲'String'。然後你可以顯示該字符串,例如'System.out.println'。詳細瞭解[使用對象和調用方法](http://docs.oracle.com/javase/tutorial/java/javaOO/),這將使其更加清晰。 – Jesper 2013-03-13 08:24:46
希望這有助於
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);
使用的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