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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:51:15  来源:igfitidea点击:

format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd

javadatetime

提问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:

三种可能的解释:

  1. your default locale is incompatible with the input date - e.g. it can't understand Sepas a month name
  2. there's something wrong with the input string, or
  3. tis the wrong type (e.g. java.sql.Dateinstead of java.util.Date, or some other type altogether), or is not declared.
  1. 您的默认语言环境与输入日期不兼容 - 例如它不能理解Sep为月份名称
  2. 输入字符串有问题,或者
  3. 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));