Java 格式日期从“MMM dd, yyyy HH:mm:ss a”到“MM.dd”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32613064/
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
format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd
提问by Nishant
I want to format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd". I have following code
我想将日期从“MMM dd, yyyy HH:mm:ss a”格式化为“MM.dd”。我有以下代码
SimpleDateFormat ft = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");
t = ft.parse(date); //Date is Sep 16, 2015 10:34:23 AM and of type string.
ft.applyPattern("MM.dd");
but I am getting exception at t = ft.parse(date);
但我在 t = ft.parse(date);
Please help
请帮忙
采纳答案by CupawnTae
Three possible explanations:
三种可能的解释:
- your default locale is incompatible with the input date - e.g. it can't understand
Sep
as a month name - there's something wrong with the input string, or
t
is the wrong type (e.g.java.sql.Date
instead ofjava.util.Date
, or some other type altogether), or is not declared.
- 您的默认语言环境与输入日期不兼容 - 例如它不能理解
Sep
为月份名称 - 输入字符串有问题,或者
t
是错误的类型(例如java.sql.Date
代替java.util.Date
,或其他类型),或未声明。
You should include details of the exception in your question to figure out which it is, but here's a working example using basically your own code, with the addition of a specific Locale
.
您应该在问题中包含异常的详细信息以找出它是哪个,但这里有一个工作示例,基本上使用您自己的代码,并添加了特定的Locale
.
SimpleDateFormat ft = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
java.util.Date t=ft.parse("Sep 16, 2015 10:34:23 AM");
ft.applyPattern("MM.dd");
System.out.println(ft.format(t));
output:
输出:
09.16
回答by rafaelasguerra
SimpleDateFormat sdf = new SimpleDateFormat("MM.dd", Locale.US);
System.out.println("Formatted Date: " + sdf.format(date));