java Jodatime 日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17450885/
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
Jodatime date format
提问by user2501165
Is it possible to format JodaTime Date.
是否可以格式化 JodaTime 日期。
Here is the code:
这是代码:
private static LocalDate priorDay(LocalDate date1) {
do {
date1 = date1.plusDays(-1);
} while (date1.getDayOfWeek() == DateTimeConstants.SUNDAY ||
date1.getDayOfWeek() == DateTimeConstants.SATURDAY);
//System.out.print(date1);
return date1;
}
Here date1 returns as: 2013-07-02but i would like as 02-JUL-13
此处 date1 返回为:2013-07-02但我希望为02-JUL-13
Thanks in advance
提前致谢
回答by Jon Skeet
Is it possible to format JodaTime Date
是否可以格式化 JodaTime 日期
Yes. You want DateTimeFormatter
.
是的。你要DateTimeFormatter
。
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yy")
.withLocale(Locale.US); // Make sure we use English month names
String text = formatter.format(date1);
That will give 02-Jul-13, but you can always upper-case it.
这将给出 02-Jul-13,但您始终可以将其大写。
See the Input and Outputpart of the user guide for more information.
有关更多信息,请参阅用户指南的输入和输出部分。
EDIT: Alternatively, as suggested by Rohit:
编辑:或者,正如 Rohit 所建议的:
String text = date1.toString("dd-MMM-yy", Locale.US);
Personally I'd prefer to create the formatter once, as a constant, and reuse it everywhere you need it, but it's up to you.
就我个人而言,我更喜欢将格式化程序创建一次,作为一个常量,并在您需要的任何地方重用它,但这取决于您。
回答by Brian Agnew
Check out the Joda DateTimeFormatter.
查看 Joda DateTimeFormatter。
You probably want to use it via something like:
您可能想通过以下方式使用它:
DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MMM-yy");
String str = fmt.print(dt);
This is a much better solution than the existing SimpleDateFormatclass. The Joda variant is thread-safe. The old Java variant is (counterintuitively) notthread-safe!
这是比现有的SimpleDateFormat类更好的解决方案。Joda 变体是线程安全的。旧的 Java 变体(违反直觉)不是线程安全的!