I want to convert java.time.LocalDate
into java.util.Date
type. Because I want to set the date into JDateChooser
. Or is there any date chooser that supports java.time
dates?
Java – Convert java.time.LocalDate into java.util.Date type
javajava-8java-time
Related Solutions
Summarize other answers I found 11 main ways to do this (see below). And I wrote some performance tests (see results below):
Ways to convert an InputStream to a String:
Using
IOUtils.toString
(Apache Utils)String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Using
CharStreams
(Guava)String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8));
Using
Scanner
(JDK)Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : "";
Using Stream API (Java 8). Warning: This solution converts different line breaks (like
\r\n
) to\n
.String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n"));
Using parallel Stream API (Java 8). Warning: This solution converts different line breaks (like
\r\n
) to\n
.String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().parallel().collect(Collectors.joining("\n"));
Using
InputStreamReader
andStringBuilder
(JDK)int bufferSize = 1024; char[] buffer = new char[bufferSize]; StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8); for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) { out.append(buffer, 0, numRead); } return out.toString();
Using
StringWriter
andIOUtils.copy
(Apache Commons)StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); return writer.toString();
Using
ByteArrayOutputStream
andinputStream.read
(JDK)ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int length; (length = inputStream.read(buffer)) != -1; ) { result.write(buffer, 0, length); } // StandardCharsets.UTF_8.name() > JDK 7 return result.toString("UTF-8");
Using
BufferedReader
(JDK). Warning: This solution converts different line breaks (like\n\r
) toline.separator
system property (for example, in Windows to "\r\n").String newLine = System.getProperty("line.separator"); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); for (String line; (line = reader.readLine()) != null; ) { if (result.length() > 0) { result.append(newLine); } result.append(line); } return result.toString();
Using
BufferedInputStream
andByteArrayOutputStream
(JDK)BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream(); for (int result = bis.read(); result != -1; result = bis.read()) { buf.write((byte) result); } // StandardCharsets.UTF_8.name() > JDK 7 return buf.toString("UTF-8");
Using
inputStream.read()
andStringBuilder
(JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)StringBuilder sb = new StringBuilder(); for (int ch; (ch = inputStream.read()) != -1; ) { sb.append((char) ch); } return sb.toString();
Warning:
Solutions 4, 5 and 9 convert different line breaks to one.
Solution 11 can't work correctly with Unicode text
Performance tests
Performance tests for small String
(length = 175), url in github (mode = Average Time, system = Linux, score 1,343 is the best):
Benchmark Mode Cnt Score Error Units
8. ByteArrayOutputStream and read (JDK) avgt 10 1,343 ± 0,028 us/op
6. InputStreamReader and StringBuilder (JDK) avgt 10 6,980 ± 0,404 us/op
10. BufferedInputStream, ByteArrayOutputStream avgt 10 7,437 ± 0,735 us/op
11. InputStream.read() and StringBuilder (JDK) avgt 10 8,977 ± 0,328 us/op
7. StringWriter and IOUtils.copy (Apache) avgt 10 10,613 ± 0,599 us/op
1. IOUtils.toString (Apache Utils) avgt 10 10,605 ± 0,527 us/op
3. Scanner (JDK) avgt 10 12,083 ± 0,293 us/op
2. CharStreams (guava) avgt 10 12,999 ± 0,514 us/op
4. Stream Api (Java 8) avgt 10 15,811 ± 0,605 us/op
9. BufferedReader (JDK) avgt 10 16,038 ± 0,711 us/op
5. parallel Stream Api (Java 8) avgt 10 21,544 ± 0,583 us/op
Performance tests for big String
(length = 50100), url in github (mode = Average Time, system = Linux, score 200,715 is the best):
Benchmark Mode Cnt Score Error Units
8. ByteArrayOutputStream and read (JDK) avgt 10 200,715 ± 18,103 us/op
1. IOUtils.toString (Apache Utils) avgt 10 300,019 ± 8,751 us/op
6. InputStreamReader and StringBuilder (JDK) avgt 10 347,616 ± 130,348 us/op
7. StringWriter and IOUtils.copy (Apache) avgt 10 352,791 ± 105,337 us/op
2. CharStreams (guava) avgt 10 420,137 ± 59,877 us/op
9. BufferedReader (JDK) avgt 10 632,028 ± 17,002 us/op
5. parallel Stream Api (Java 8) avgt 10 662,999 ± 46,199 us/op
4. Stream Api (Java 8) avgt 10 701,269 ± 82,296 us/op
10. BufferedInputStream, ByteArrayOutputStream avgt 10 740,837 ± 5,613 us/op
3. Scanner (JDK) avgt 10 751,417 ± 62,026 us/op
11. InputStream.read() and StringBuilder (JDK) avgt 10 2919,350 ± 1101,942 us/op
Graphs (performance tests depending on Input Stream length in Windows 7 system)
Performance test (Average Time) depending on Input Stream length in Windows 7 system:
length 182 546 1092 3276 9828 29484 58968
test8 0.38 0.938 1.868 4.448 13.412 36.459 72.708
test4 2.362 3.609 5.573 12.769 40.74 81.415 159.864
test5 3.881 5.075 6.904 14.123 50.258 129.937 166.162
test9 2.237 3.493 5.422 11.977 45.98 89.336 177.39
test6 1.261 2.12 4.38 10.698 31.821 86.106 186.636
test7 1.601 2.391 3.646 8.367 38.196 110.221 211.016
test1 1.529 2.381 3.527 8.411 40.551 105.16 212.573
test3 3.035 3.934 8.606 20.858 61.571 118.744 235.428
test2 3.136 6.238 10.508 33.48 43.532 118.044 239.481
test10 1.593 4.736 7.527 20.557 59.856 162.907 323.147
test11 3.913 11.506 23.26 68.644 207.591 600.444 1211.545
That's the hard way, and those java.util.Date
setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole java.util.Date
class was de-facto deprecated (discommended) since introduction of java.time
API in Java 8 (2014).
Simply format the date using DateTimeFormatter
with a pattern matching the input string (the tutorial is available here).
In your specific case of "January 2, 2010" as the input string:
- "January" is the full text month, so use the
MMMM
pattern for it - "2" is the short day-of-month, so use the
d
pattern for it. - "2010" is the 4-digit year, so use the
yyyy
pattern for it.
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 a 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 an 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
).
Pre-Java 8
In case you're not on Java 8 yet, or are forced to use java.util.Date
, then format the date using SimpleDateFormat
using a format pattern matching the input string.
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 the 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 four characters or more represent 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 |
An 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 it from different methods/threads. You should always create it brand new within the method local scope.
Related Topic
- Java – How to convert a String to an int in Java
- Java – How to use Jackson to deserialise an array of objects
- Java – Converting between java.time.LocalDateTime and java.util.Date
- Java 8 List
into Map - R – Product key Registration – Visual Basic
- Java – How to parse/format dates with LocalDateTime? (Java 8)
- Java – Differences between Java 8 Date Time API (java.time) and Joda-Time
Best Answer
That assumes your date chooser uses the system default timezone to transform dates into strings.