java 将日期转换为特定格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10006759/
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
Convert date into specific format
提问by dhananjay
I am working on Java. I have a date for example: 20120328.
Year is 2012, month is 03 & day is 28.
I want to convert it into yyyy-MM-dd
format.
I have tried it but it is not working.
How to do it?
我正在研究 Java。我有一个日期,例如:20120328。
年份是 2012,月份是 03,天是 28。
我想将其转换为yyyy-MM-dd
格式。
我已经尝试过了,但它不起作用。
怎么做?
采纳答案by Ravindra Gullapalli
First you create the format using substring like
首先,您使用子字符串创建格式,例如
String myDate = "20120328";
String myConvertedDate = myDate.substring(0,4) + "-" + myDate.substring(5,6) + "-" + myDate.substring(7);
This produces the date as 2012-03-28
这产生的日期为2012-03-28
Then use simple date format to convert that into date if required.
如果需要,然后使用简单的日期格式将其转换为日期。
回答by Chaitu
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
If you want other than "MM/dd/yyyy" then just change the format in SimpleDateFormat
如果您想要“MM/dd/yyyy”以外的其他内容,则只需更改SimpleDateFormat 中的格式
回答by vkantiya
回答by npinti
回答by Bruce wayne - The Geek Killer
You can use this one for Date formatting
您可以使用此日期格式
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
And this one for getting TimeStamp
而这个用于获取时间戳
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Timestamp timestamp =timestamp=new Timestamp(System.currentTimeMillis());
String ourformat = formatter.format(timestamp);