Java string to date conversion

0 votes

What is 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.

Dec 29, 2020 in Java by anonymous
• 8,910 points
1,265 views

2 answers to this question.

0 votes

That's the hard way and those java.util.Date setter methods have been deprecated since Java 1.1 (1997). Simply format the date using SimpleDateFormat using a format pattern matching the input string.

In your specific case of "January 2, 2010" as the input string:

  1. "January" is the full text month, so use the MMMM pattern for it
  2. "2" is the short day-of-month, so use the d pattern for it.
  3. "2010" is the 4-digit year, so use the 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 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

Hope this helps!

Get your Java Certification today and become certified.

Thanks!

answered Dec 29, 2020 by Gitika
• 65,890 points

edited Jul 4, 2023 by Khan Sarfaraz
0 votes

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

import java.text.SimpleDateFormat;  

import java.util.Date;  

public class StringToDateExample1 {  

public static void main(String[] args)throws Exception {  

    String sDate1="31/12/1998";  

    Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);  

    System.out.println(sDate1+"\t"+date1);  

}  

}  
  1. Output:

    31/12/1998	Thu Dec 31 00:00:00 IST 1998
answered Dec 29, 2020 by Nikita

Related Questions In Java

0 votes
2 answers

Integer to String conversion in java

We can do this in 2 ways: String ...READ MORE

answered Jul 28, 2018 in Java by samarth295
• 2,220 points
1,079 views
0 votes
3 answers

String to Double conversion in java

Double temp = Double.valueOf(str); number = temp.doubleValue(); READ MORE

answered Sep 10, 2018 in Java by Sushmita
• 6,920 points
1,656 views
0 votes
1 answer

Converting ISO 8601-compliant String to java.util.Date

Unfortunately, the time zone formats available to SimpleDateFormat (Java ...READ MORE

answered Nov 27, 2018 in Java by Daisy
• 8,140 points

edited Oct 7, 2021 by Sarfaraz 9,660 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 59,230 points
2,233 views
+1 vote
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,620 points
1,258 views
+1 vote
1 answer

Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

answered Jun 26, 2018 in Java by scarlett
• 1,290 points
1,150 views
+1 vote
3 answers

What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,220 points
3,467 views
0 votes
2 answers

What is the syntax to initialize an array?

Rather than learning un-Official websites learn from ...READ MORE

answered Aug 2, 2018 in Java by samarth295
• 2,220 points
910 views
+17 votes
25 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7, 2019 in Java by Suresh
• 720 points
253,309 views
+1 vote
4 answers

What is a simple way to repeat a string in java?

There is already answer wriiten using StringBuilder ...READ MORE

answered Dec 16, 2020 in Java by Rajiv
• 8,910 points
29,155 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP