java.util.Date 格式转换 yyyy-mm-dd 到 mm-dd-yyyy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18480633/
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
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
提问by user182944
I have a java.util.Date
in the format yyyy-mm-dd
. I want it to be in the format mm-dd-yyyy
我有一个java.util.Date
格式yyyy-mm-dd
。我想要它的格式mm-dd-yyyy
Below is the sample util I tried out for this conversion:
以下是我为此转换尝试的示例实用程序:
// Setting the pattern
SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
// myDate is the java.util.Date in yyyy-mm-dd format
// Converting it into String using formatter
String strDate = sm.format(myDate);
//Converting the String back to java.util.Date
Date dt = sm.parse(strDate);
Still the output I am getting is not in the format mm-dd-yyyy
.
我得到的输出仍然不是格式mm-dd-yyyy
。
Kindly let me know how to format a java.util.Date
from yyyy-mm-dd
to mm-dd-yyyy
请让我知道如何格式化java.util.Date
从yyyy-mm-dd
到mm-dd-yyyy
采纳答案by MadProgrammer
Date
is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).
Date
是自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来毫秒数的容器。
It has no concept of format.
它没有格式的概念。
Java 8+
Java 8+
LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);
Outputs...
输出...
05-11-2018
2018-05-11
2018-05-11T17:24:42.980
Java 7-
爪哇 7-
You should be making use of the ThreeTen Backport
您应该使用ThreeTen Backport
Original Answer
原答案
For example...
例如...
Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);
Outputs...
输出...
Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013
None of the formatting has changed the underlying Date
value. This is the purpose of the DateFormatter
s
没有任何格式改变了基础Date
值。这就是DateFormatter
s的目的
Updated with additional example
更新了附加示例
Just in case the first example didn't make sense...
以防万一第一个例子没有意义......
This example uses two formatters to format the same date. I then use these same formatters to parse the String
values back to Date
s. The resulting parse does not alter the way Date
reports it's value.
此示例使用两个格式化程序来格式化相同的日期。然后我使用这些相同的格式化程序将String
值解析回Date
s。生成的解析不会改变Date
报告其值的方式。
Date#toString
is just a dump of it's contents. You can't change this, but you can format the Date
object any way you like
Date#toString
只是其内容的转储。您无法更改此设置,但您可以按Date
您喜欢的任何方式设置对象格式
try {
Date myDate = new Date();
System.out.println(myDate);
SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);
// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}
Which outputs...
哪个输出...
Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013
Also, be careful of the format patterns. Take a closer look at SimpleDateFormat
to make sure you're not using the wrong patterns ;)
另外,请注意格式模式。仔细查看SimpleDateFormat
以确保您没有使用错误的模式;)
回答by newuser
SimpleDateFormat("MM-dd-yyyy");
instead of
代替
SimpleDateFormat("mm-dd-yyyy");
because MM points Month
, mm points minutes
因为MM points Month
,mm points minutes
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
回答by darshakat
'M' (Capital) represent month & 'm' (Simple) represent minutes
'M' (Capital) 代表月 & 'm' (Simple) 代表分钟
Some example for months
几个月的一些例子
'M' -> 7 (without prefix 0 if it is single digit)
'M' -> 12
'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12
'MMM' -> Jul (display with 3 character)
'MMMM' -> December (display with full name)
Some example for minutes
分钟的一些例子
'm' -> 3 (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19
回答by Dilip
Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.
请将小“mm”月份改为大写“MM”即可。下面是示例代码供参考。
**Date myDate = new Date();
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
Date dt = sm.parse(strDate);
System.out.println(strDate);**
回答by Basil Bourque
tl;dr
tl;博士
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)
Details
细节
I have a java.util.Date in the format yyyy-mm-dd
我有一个格式为 yyyy-mm-dd 的 java.util.Date
As other mentioned, the Date
class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.
正如其他人提到的,Date
该类没有格式。自 UTC 时间 1970 年开始以来,它有一个毫秒计数。没有任何附加条件。
java.time
时间
The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.
其他答案使用麻烦的旧的遗留日期时间类,现在被 java.time 类取代。
If you have a java.util.Date
, convert to a Instant
object. The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).
如果您有java.util.Date
,则转换为Instant
对象。该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
Instant instant = myUtilDate.toInstant();
Time zone
时区
The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
其他答案忽略了时区的关键问题。确定日期需要时区。对于任何给定时刻,日期因地区而异。午夜过后几分钟在巴黎法国是新的一天,而在魁北克蒙特利尔仍然是“昨天”。
Define the time zone by which you want context for your Instant
.
定义您希望Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Apply the ZoneId
to get a ZonedDateTime
.
应用ZoneId
以获得ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( z );
LocalDate
LocalDate
If you only care about the date without a time-of-day, extract a LocalDate
.
如果您只关心日期而不关心时间,请提取LocalDate
.
LocalDate localDate = zdt.toLocalDate();
To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString
. The java.time classes use the standard formats by default when generating/parsing strings.
要生成标准 ISO 8601 格式的字符串,YYYY-MM-DD,只需调用toString
. java.time 类在生成/解析字符串时默认使用标准格式。
String output = localDate.toString();
2017-01-23
2017-01-23
If you want a MM-DD-YYYY format, define a formatting pattern.
如果您需要 MM-DD-YYYY 格式,请定义格式模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );
Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm
(minute of hour) rather than MM
(month of year).
请注意,格式模式代码区分大小写。问题中的代码错误使用mm
(小时的分钟)而不是MM
(年的月份)。
Use the same DateTimeFormatter
object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.
使用相同的DateTimeFormatter
对象进行解析。java.time 类是线程安全的,因此您可以保留此对象并在多个线程之间重复使用它。
LocalDate localDate = LocalDate.parse( "01-23-2017" , f );
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8and SE 9and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8和SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by Ujitha
It is simple use below codes.
下面的代码使用起来很简单。
final Date todayDate = new Date();
System.out.println(todayDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(todayDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(todayDate));
System.out.println(todayDate);