Java string to date conversion -


can recommend best way convert string in format 'january 2, 2010' date in java? ultimately, want break out month, day, , year integers can use:

date date = new date(); date.setmonth().. date.setyear().. date.setday().. date.setlong currenttime = date.gettime(); 

to convert date time.

don't it, that's hard way. moreover, setter methods of java.util.date deprecated since java 1.1 (1997). simply format date using simpledateformat using format pattern matching input string.

in specific case of "january 2, 2010" input string, "january" full text month, use mmmm pattern it, "2" short day-of-month, use d pattern it, "2010" 4-digit year, use yyyy pattern 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 importance of explicit locale argument. if omit it, use default locale not english used in month name of input string. if locale doesn't match input string, confusingly java.text.parseexception though when format pattern seems valid.

here's extract of relevance the javadoc, listing 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       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 patterns case sensitive , text based patterns of 4 characters or more represents full form, otherwise short or abbreviated form used if available. e.g. mmmmm or more unnecessary.

here examples of valid simpledateformat patterns parse given string date:

input string                            pattern ------------------------------------    ---------------------------- 2001.07.04 ad @ 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 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 simpledateformat not thread safe. in other words, should never declare , assign static or instance variable , reuse different methods/threads. should create brand new within method local scope.


java 8 update

if happen on java 8 already, use datetimeformatter (also here, click link see predefined formatters , available format patterns; the tutorial available here). new api inspired 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 format pattern happens contain time part well, use localdatetime#parse(text, formatter) instead of localdate#parse(text, formatter). and, if format pattern happens contain time zone well, use zoneddatetime#parse(text, formatter) instead.

here's extract of relevance the javadoc, listing available format patterns:

symbol  meaning                     presentation  examples ------  --------------------------  ------------  ---------------------------------------------- g       era                         text          ad; anno domini; 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        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       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' 0    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 has several predefined formatters more popular patterns. instead of e.g. datetimeformatter.ofpattern("eee, d mmm yyyy hh:mm:ss z", locale.english);, use datetimeformatter.rfc_1123_date_time. possible because are, on contrary simpledateformat, thread safe. define own, if necessary.

for particular input string format, don't need use explicit datetimeformatter: standard iso 8601 date, 2016-09-26t17:44:57z, can parsed directly localdatetime#parse(text) uses iso_local_date_time formatter. similarly, localdate#parse(text) parses iso date without time component (see iso_local_date), , zoneddatetime#parse(text) parses iso date offset , time zone added (see iso_zoned_date_time).


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -