You are on page 1of 4

3/3/2017 ParseStringtoDatewithDifferentFormatinJavaStackOverflow

xDismiss

JointheStackOverflowCommunity

Stack Overflow is a community of 6.8 million


programmers, just like you, helping each other.
Join them it only takes a minute:

Signup

ParseStringtoDatewithDifferentFormatinJava

Iwanttoconvert String to Date indifferentformats.

Forexample,

Iamgettingfromuser,

StringfromDate="19/05/2009";//i.e.(dd/MM/yyyy)format

Iwanttoconvertthis fromDate asaDateobjectof "yyyyMMdd" format

HowcanIdothis?

java string date

editedOct1'14at11:49 askedMay19'09at12:22
Community GnaniyarZubair
1 1 2,619 17 43 64

1 ADateobjecthasnoformat,itisjustanumberrepresentingthedate.Thedatecanberepresentedbya
Stringwiththeformatof"yyyyMMdd".CarlosHeubergerMay19'09at13:58

7Answers

Takealookat SimpleDateFormat .Thecodegoessomethinglikethis:

SimpleDateFormatfromUser=newSimpleDateFormat("dd/MM/yyyy");
SimpleDateFormatmyFormat=newSimpleDateFormat("yyyyMMdd");

try{

StringreformattedStr=myFormat.format(fromUser.parse(inputString));
}catch(ParseExceptione){
e.printStackTrace();
}

editedJan11'13at19:35 answeredMay19'09at12:31
AlexCio MichaelMyers
4,125 4 26 62 128k 31 237 269

insteadofgettingstringformat,canigetoutputin Date format? Rachel Apr20'12at14:01

2 @Rachel:Sure,justuse parse anddon'tgoonto format . parse parsesaStringtoaDate.


MichaelMyers Apr20'12at14:19

1 But parse givesmein dateformat as FriJan0600:01:00EST2012 butitneedin 20120106


dateformatRachelApr20'12at14:23

http://stackoverflow.com/questions/882420/parsestringtodatewithdifferentformatinjava 1/4
3/3/2017 ParseStringtoDatewithDifferentFormatinJavaStackOverflow
@Rachelitisbecausewhenyoucall System.out.println(anyDateObject) thedefaulttoString()method
iscalledwhichhasbeensaidtoprintinthatformate.g. FriJan0600:01:00EST2012 .Youneedto
overrideittosuityourneeds.KNUFeb28'14at7:07

@Rachelyoumustsee toString()forDateClass tounderstandingwhyitworksthatway. KNU Feb28'14


at7:16

Usethe SimpleDateFormat class:

privateDateparseDate(Stringdate,Stringformat)throwsParseException
{
SimpleDateFormatformatter=newSimpleDateFormat(format);
returnformatter.parse(date);
}

Usage:

Datedate=parseDate("19/05/2009","dd/MM/yyyy");

Forefficiency,youwouldwanttostoreyourformattersinahashmap.Thehashmapisastatic
memberofyourutilclass.

privatestaticMap<String,SimpleDateFormat>hashFormatters=newHashMap<String,
SimpleDateFormat>();

publicstaticDateparseDate(Stringdate,Stringformat)throwsParseException
{
SimpleDateFormatformatter=hashFormatters.get(format);

if(formatter==null)
{
formatter=newSimpleDateFormat(format);
hashFormatters.put(format,formatter);
}

returnformatter.parse(date);
}

editedApr30'16at8:23 answeredMay19'09at12:31
BasheerALMOMANI Agora
1,774 12 23 162 6

7 CAVEAT!!Theideaisgood,buttheimplementationisnot.DateFormatsmustnotbestoredstatically,
becausetheyarenotthreadsafe!Iftheyareusedfrommorethanonethread(andthisisalwaysriskywith
statics).FindBugscontainsadetectorforthis(whichIhappenedtocontributeinitially,afterIgotbitten.
Seedschneller.blogspot.com/2007/04/:))DanielSchnellerMay19'09at12:54

Yourblogentryisaninterestingread:)WhatiftheparseDatemethoditselfisynchronized?Theproblem
thoughisthatitwouldprobablyslowthecodedown...AgoraMay19'09at13:05

1 AslongastheparseDatemethodwastheonlymethodaccessingthemap,synchronizingitwouldwork.
Howeverthiswouldasyousayintroduceabottleneck.DanielSchnellerMay19'09at13:24

Checkthejavadocsfor java.text.SimpleDateFormat Itdescribeseverything


youneed.

editedFeb29'12at9:10 answeredMay19'09at12:28
bluish Matt
10.3k 12 74 130 1,725 12 15

Convertastringdatetojava.sql.Date

StringfromDate="19/05/2009";
DateFormatdf=newSimpleDateFormat("dd/MM/yyyy");
java.util.Datedtt=df.parse(fromDate);
java.sql.Dateds=newjava.sql.Date(dtt.getTime());
System.out.println(ds);//MonJul0500:00:00IST2010

editedAug1'13at22:24 answeredAug21'12at7:01
EricLeschinski RiteshKaushik
53.4k 27 236 203 321 1 6 13

While SimpleDateFormat willindeedworkforyourneeds,additionallyyoumightwanttocheckout


JodaTime,whichisapparentlythebasisfortheredoneDatelibraryinJava7.WhileIhaven't

http://stackoverflow.com/questions/882420/parsestringtodatewithdifferentformatinjava 2/4
3/3/2017 ParseStringtoDatewithDifferentFormatinJavaStackOverflow
useditalot,I'veheardnothingbutgoodthingsaboutitandifyourmanipulatingdatesextensively
inyourprojectsitwouldprobablybeworthlookinginto.

editedApr30'16at7:58 answeredMay19'09at12:45
BasheerALMOMANI JamesMcMahon
1,774 12 23 24.1k 52 152 228

Jodaisgood!Yay!SteveMcLeodMay19'09at12:50

Simplewaytoformatadateandconvertintostring

Datedate=newDate();

StringdateStr=String.format("%td/%tm/%tY",date,date,date);

System.out.println("Datewithformatofdd/mm/dd:"+dateStr);

output:Datewithformatofdd/mm/dd:21/10/2015

answeredOct21'15at5:35
KhalidHabib
640 6 13

tldr

LocalDate.parse(
"19/05/2009",
DateTimeFormatter.ofPattern("dd/MM/uuuu")
)

Details
TheotherAnswerswith java.util.Date , java.sql.Date ,and SimpleDateFormat arenow
outdated.

LocalDate

Themodernwaytododatetimeisworkwiththejava.timeclasses,specifically LocalDate .The


LocalDate classrepresentsadateonlyvaluewithouttimeofdayandwithouttimezone.

DateTimeFormatter

Toparse,orgenerate,aStringrepresentingadatetimevalue,usethe DateTimeFormatter class.

DateTimeFormatterf=DateTimeFormatter.ofPattern("dd/MM/uuuu");
LocalDateld=LocalDate.parse("19/05/2009",f);

DonotconflateadatetimeobjectwithaStringrepresentingitsvalue.Adatetimeobjecthasno
format,whileaStringdoes.Adatetimeobject,suchas LocalDate ,cangenerateaStringto
representitsinternalvalue,butthedatetimeobjectandtheStringareseparatedistinctobjects.

YoucanspecifyanycustomformattogenerateaString.Orletjava.timedotheworkof
automaticallylocalizing.

DateTimeFormatterf=
DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
.withLocale(Locale.CANADA_FRENCH);
Stringoutput=ld.format(f);

Dumptoconsole.

System.out.println("ld:"+ld+"|output:"+output);

ld:20090519|output:mardi19mai2009

SeeinactioninIdeOne.com.

Aboutjava.time

http://stackoverflow.com/questions/882420/parsestringtodatewithdifferentformatinjava 3/4
3/3/2017 ParseStringtoDatewithDifferentFormatinJavaStackOverflow
Thejava.timeframeworkisbuiltintoJava8andlater.Theseclassessupplantthetroublesome
oldlegacy datetimeclassessuchas java.util.Date , Calendar ,& SimpleDateFormat .

TheJodaTimeproject,nowinmaintenancemode,advisesmigrationtojava.time.

Tolearnmore,seetheOracleTutorial.AndsearchStackOverflowformanyexamplesand
explanations.SpecificationisJSR310.

Wheretoobtainthejava.timeclasses?

JavaSE8andSE9andlater
Builtin.
PartofthestandardJavaAPIwithabundledimplementation.
Java9addssomeminorfeaturesandfixes.
JavaSE6andSE7
Muchofthejava.timefunctionalityisbackportedtoJava6&7inThreeTenBackport.
Android
TheThreeTenABPprojectadaptsThreeTenBackport(mentionedabove)forAndroid
specifically.
SeeHowtouse.

TheThreeTenExtraprojectextendsjava.timewithadditionalclasses.Thisprojectisaproving
groundforpossiblefutureadditionstojava.time.Youmayfindsomeusefulclassesheresuchas
Interval , YearWeek , YearQuarter ,andmore.

editedOct26'16at0:50 answeredOct26'16at0:18
BasilBourque
47.6k 13 162 212

http://stackoverflow.com/questions/882420/parsestringtodatewithdifferentformatinjava 4/4

You might also like