Java字符串到日期转换 [英] Java string to date conversion
问题描述
日期日期= new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
将日期转换为时间。
不要这样做,那是很困难的。此外,自Java 1.1(1997)以来,这些 java.util.Date
的setter方法已被弃用。 使用使用匹配输入字符串的格式模式
。
在您的具体情况下,2010年1月2日作为输入字符串,1月是全文月份,因此使用 MMMM
模式,2是短日期,因此使用 d
模式,2010是4位数的年份,因此使用 yyyy
模式。
String string =2010年1月2日;
DateFormat format = new SimpleDateFormat(MMMM d,yyyy,Locale.ENGLISH);
日期date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010
请注意显式 Locale
参数。如果你省略它,那么它将使用默认区域设置,它不一定是输入字符串的月份名称中使用的英文。如果区域设置与输入字符串不匹配,那么即使格式模式似乎有效,您也会混淆地得到一个 java.text.ParseException
。
以下是从 javadoc ,列出所有可用的格式模式:
时间组件演示示例
------ ---------------------- -------------- ---- -------------------------------------
G Era指示符文本AD $ b $按年度1996年; 96
Y周年2009; 09
M / L月份月份月份;七月07
w年份周数27
W月份周数2
D一年中的日数189
d一天中的月份数10
F月份的星期数2
E星期二文字星期二; Tue
u日数周数1
a Am / pm标记文本PM
H小时(0-23)数0
k小时(1-24)数字24
K小时在上午/下午(0-11)号码0
h上午/下午(1-12)小时数12
m分钟小时数30
s第二分钟数55
S毫秒数978
z时区一般时区太平洋标准时间;太平洋标准时间; GMT-08:00
Z时区RFC 822时区-0800
X时区ISO 8601时区-08; -0800; -08:00
请注意,模式区分大小写,4个字符或更多的基于文本的模式表示完整的表格,否则如果有的话,使用简短或缩写形式。例如 MMMMM
或更多是不必要的。
以下是一些有效的 SimpleDateFormat
pattern to parse a given string to date:
输入字符串模式
------------------------------------ ------------- ---------------
2001.07.04 AD在12:08:56 PDT yyyy.MM.dd G'at'HH:mm:ss z
Wed ,7月4日,'01 EEE,MMM d,''yy
12:08 PM h:mm a
12点钟PM,太平洋夏令时间hh'o''clock'a,zzzz
0:08 PM,PDT K:mm a,z
02001.July.04 AD 12:08 PM yyyyyMMMM.dd GGG hh:mm aaa
星期三,2001年7月4日12: 08:56 -0700 EEE,d MMM yyyy HH:mm:ss Z
010704120856-0700 yyMMddHHmmssZ
2001-07-04T12:08:56.235-0700 yyyy-MM-dd'THH:mm :ss.SSSZ
2001-07-04T12:08:56.235-07:00 yyyy-MM-dd'THH:mm:ss.SSSXXX
2001-W27-3 YYYY-'W'ww-u
重要提示是 SimpleDateFormat
是不线程安全。换句话说,您不应该声明并将其分配为静态或实例变量,然后从不同的方法/线程重用。您应该始终在本地范围的方法中创建全新的。
Java 8更新
如果您刚刚使用Java 8,请使用 DateTimeFormatter
(另请点击链接查看所有预定义的格式化程序和可用的格式模式; 本教程可在此处)。这个新API的灵感来自于 JodaTime 。
String string =2010年1月2日;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(MMMM d,yyyy,Locale.ENGLISH);
LocalDate date = LocalDate.parse(string,formatter);
System.out.println(date); // 2010-01-02
注意:如果您的格式模式也包含时间部分,然后使用 LocalDateTime#parse(text,formatter)
而不是 LocalDate#parse(text,格式化程序)
。而且,如果您的格式模式也包含时区,那么请使用 ZonedDateTime#parse(text,formatter)
, p>
以下是与 javadoc ,列出所有可用的格式模式:
符号含义演示文稿
------ -------------------------- -------- ---- ----------------------------------------------
G时代文字AD;公元; 2004年A
04年
年2004年; 04
D日期数189
年/月数/文字7; 07;七月七月; J
d月日数10
Q / q季度数/文字3; 03; Q3;第三季度
Y年度1996年; 96
w周周周数27
W周数月4日
E周日文字星期二;星期二; t
e / c本地化星期数/文字2; 02;星期二星期二; T
F每周月份数3
a am-pm-of-day text PM
h时钟上午pm(1-12)数字12
K hour-of-pm-pm(0-11)number 0
k clock-hour-of-am-pm(1-24)number 0
H hour-当天(0-23)数0
m分钟小时数30
s秒数55
秒分数978
A milli - 天数1234
n纳秒秒数987654321
N纳日数1234000000
V时区ID区域号美国/ Los_Angeles; Z; -08:30
z时区名称zone-name太平洋标准时间; PST
O本地化区域偏移offset O O GMT + 8; GMT + 08:00; UTC-08:00;
零偏移-X Z的区域偏移'Z'; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z区域偏移量偏移量-Z +0000; -0800; -08:00;
请注意,它有几个预定义格式化程序。所以代替例如 DateTimeFormatter.ofPattern(EEE,d MMM yyyy HH:mm:ss Z,Locale.ENGLISH);
,您可以使用 DateTimeFormatter.RFC_1123_DATE_TIME
。这是可能的,因为它们与 SimpleDateFormat
相反,线程安全。如果需要,您也可以自己定义。
对于特定的输入字符串格式,您不需要使用明确的 DateTimeFormatter
:一个标准的 ISO 8601 日期,如2016-09-26T17:44: 57Z,可以直接用
LocalDateTime#parse(text)
,因为它已经使用了 ISO_LOCAL_DATE_TIME
格式化程序。同样, LocalDate#parse(text)
解析没有时间组件的ISO日期(请参阅 ISO_LOCAL_DATE
)和 ZonedDateTime#parse(text )
解析添加偏移和时区的ISO日期(请参阅 ISO_ZONED_DATE_TIME
)。
Can somebody recommend the best way to convert a string in the format 'January 2, 2010' to a date in java? Ultimately, I want to break out the month, the day, and the year as integers so that I can use:
Date date = new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
to convert the date into time.
Don't do it, that's the hard way. Moreover, those setter methods of java.util.Date
are deprecated since Java 1.1 (1997). Simply format date using SimpleDateFormat
using a format pattern matching the input string.
In your specific case of "January 2, 2010" as input string, "January" is the full text month, so use MMMM
pattern for it, "2" is the short day-of-month, so use d
pattern for it, "2010" is the 4-digit year, so use yyyy
pattern for it.
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010
Note the importance of explicit Locale
argument. If you omit it, then it will use the default locale which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a java.text.ParseException
even though when the format pattern seems valid.
Here's an extract of relevance from the javadoc, listing all available format patterns:
Letter Date or Time Component Presentation Examples
------ ---------------------- ------------------ -------------------------------------
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M/L Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
Note that the patterns are case sensitive and that text based patterns of 4 characters or more represents the full form, otherwise a short or abbreviated form is used if available. So e.g. MMMMM
or more is unnecessary.
Here are some examples of valid SimpleDateFormat
patterns to parse a given string to date:
Input string Pattern
------------------------------------ ----------------------------
2001.07.04 AD at 12:08:56 PDT yyyy.MM.dd G 'at' HH:mm:ss z
Wed, Jul 4, '01 EEE, MMM d, ''yy
12:08 PM h:mm a
12 o'clock PM, Pacific Daylight Time hh 'o''clock' a, zzzz
0:08 PM, PDT K:mm a, z
02001.July.04 AD 12:08 PM yyyyy.MMMM.dd GGG hh:mm aaa
Wed, 4 Jul 2001 12:08:56 -0700 EEE, d MMM yyyy HH:mm:ss Z
010704120856-0700 yyMMddHHmmssZ
2001-07-04T12:08:56.235-0700 yyyy-MM-dd'T'HH:mm:ss.SSSZ
2001-07-04T12:08:56.235-07:00 yyyy-MM-dd'T'HH:mm:ss.SSSXXX
2001-W27-3 YYYY-'W'ww-u
Important note is that SimpleDateFormat
is not thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse from different methods/threads. You should always create it brand new within the method local scope.
Java 8 update
If you happen to be on Java 8 already, then use DateTimeFormatter
(also here, click the link to see all predefined formatters and available format patterns; the tutorial is available here). This new API is inspired by JodaTime.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02
Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter)
instead of LocalDate#parse(text, formatter)
. And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter)
instead.
Here's an extract of relevance from the javadoc, listing all available format patterns:
Symbol Meaning Presentation Examples
------ -------------------------- ------------ ----------------------------------------------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
Do note that it has several predefined formatters for the more popular patterns. So instead of e.g. DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
, you could use DateTimeFormatter.RFC_1123_DATE_TIME
. This is possible because they are, on the contrary to SimpleDateFormat
, thread safe. You could thus also define your own, if necessary.
For particular input string format, you don't need to use an explicit DateTimeFormatter
: a standard ISO 8601 date, like 2016-09-26T17:44:57Z, can be parsed directly with LocalDateTime#parse(text)
as it already uses the ISO_LOCAL_DATE_TIME
formatter. Similarly, LocalDate#parse(text)
parses a ISO date without the time component (see ISO_LOCAL_DATE
), and ZonedDateTime#parse(text)
parses an ISO date with an offset and time zone added (see ISO_ZONED_DATE_TIME
).
这篇关于Java字符串到日期转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!