java 将日期格式更改为 mm-dd-yyyy hh:mm
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15379165/
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
Changing the date format to mm-dd-yyyy hh:mm
提问by Little bird
I'm trying to use this code:
我正在尝试使用此代码:
private static Date getTimeStamp() {
return new Timestamp(new Date().getTime());
}
What I'm getting is 2013-03-13 12:46:22.011
我得到的是 2013-03-13 12:46:22.011
But what I need is that the timestamp should be in the format of mm-dd-yyyy hh:mm
.
但我需要的是时间戳的格式应该是mm-dd-yyyy hh:mm
.
回答by Jesper
java.sql.Timestamp
objects (just like java.util.Date
and java.sql.Date
) do not have a format by themselves, so you cannot "have a Timestamp in the format [whatever]".
java.sql.Timestamp
对象(就像java.util.Date
and java.sql.Date
)本身没有格式,所以你不能“有格式[任何]的时间戳”。
A format only is applicable when you convert the object to a string for display. You can use SimpleDateFormat
to convert a Timestamp
to a string, using the format you want.
仅当您将对象转换为字符串进行显示时,格式才适用。您可以使用所需的格式SimpleDateFormat
将 a 转换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);
回答by zennith
Hope this helps
希望这可以帮助
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);
回答by JWill
You can use SimpleDateFormat http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.htmlto achieve your goal.
您可以使用 SimpleDateFormat http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html来实现您的目标。
For Example: new SimpleDateFormat("MM-dd-yyyy HH:mm").format(timestamp));
例如: new SimpleDateFormat("MM-dd-yyyy HH:mm").format(timestamp));