I need to format a date(yyyyMMDD) into YYYY-MM-DD. Can I create a date format of the latter ?
Yes.
Use SimpleDateFormat.
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
String sourceDateStr = "20101012";
try {
Date sourceDate = sourceFormat.parse(sourceDateStr);
String targetDateStr = targetFormat.format(sourceDate);
System.out.println(targetDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Gives the output 2010-01-12
You can use a pre-written class like the pojava http://www.pojava.org/ for this.
It's very good a recognising different date formats and translating between them.
For example, to translate between the formats above:
try {
System.out.println("Date:" + new DateTime("Date").toString("yyyy-MM-dd"));
} catch (Exception error) {
error.printStackTrace();
}
I find that using this class helps as I don't have to worry too much about the different date formats that exist out there (except between UK/US dd/MM/yyyy & MM/dd/yyyy, which you can specifically configure the class for)
Have a look at joda-time: http://joda-time.sourceforge.net/
Related
I would like to parse String to Date. The problem is that if I parse the wrong date like "2009-02-40" I don't get any exception (no feedback that I passed wrong date) instead I get Date object set to "2009-01-01".
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
try {
Date result = df.parse("2009-02-40");
System.out.println(result);
} catch (ParseException e) {
e.printStackTrace();
}
How to get an exception when I pass the wrong Date like this one above?
Try following code:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
df.setLenient(false); //note the change here
try {
Date result = df.parse("2009-02-40");
System.out.println(result);
} catch (ParseException e) {
e.printStackTrace();
}
You want to call setLenient(false) on your formater. This causes "strict" checking when parsing takes places. By default, "lenient" is "true; and then some heuristics are used that turn "garbage in" into whatever.
Probably not the best design in the world; but that is how it works.
df.parse("2009-02-40"); will throw ParseException, if the beginning of the specified string cannot be parsed.
For a strict parsing, use df.setLenient(false);
I am trying to parse a date in Korean Date format using SimpleDateFormat which works. However i would like to remove any dependency on adding up Korean Characters in Pattern for Year(년), Month(월) and Day(일) and so on.
String dateinKorean = "2013년 9월 26일 (목)";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy'년' M'월' d'일' '('EE')'", Locale.KOREA);
try {
Date dt = sdf.parse(dateinKorean);
System.out.println(dt.toGMTString());
} catch (ParseException e) {
e.printStackTrace();
}
I am trying to use DateFormatSymbols Class to Parse the date using the Locale, however the problem is I am not able to parse the complete date, I can parse an individual Month(MM), Year(yyyy) or Day(dd) without any issues.
DateFormatSymbols df = DateFormatSymbols.getInstance(Locale.KOREAN);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd", df);
try {
// 2013년 9월 26일
Date dt = sdf.parse("2013년 9월 26일");
} catch (ParseException e) {
}
Can anyone please help me identify if there is any other way to parse the dates other than shown above ?
If the date format includes "fixed" characters they are used as-is, so if you include words like "year" or "month" in the format they cannot be ignored.
You can hack your way around this by removing all non-digits from the string before parsing, for example:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", df);
Date dt = sdf.parse("2013년 9월 26일".replaceAll("\\D+", "-"));
A better solution could be internationalizing the date format so that each language you support could have a format of its own.
I have this simple program I've written
try{
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
sdf.setLenient(false);
//Date date = sdf.parse("1/14/1999"); Apologies for confusion
Date date = sdf.parse(request.getParameter("selectedDate"));
}catch(ParseException ex){
ex.printStackTrace();
}
From what I understand a ParseException will be thrown if the date is out of range or the format given is wrong. I want to be able to tell them apart. How can I can achieve this ?
Edit: When I said out of range I meant something like this 15/15/1999. That's why setLenient(false)
ParseException doesn't offer a reliably way of determining the cause of the exception itself. You could invoke parse twice setting lenient to true and false and checking its state in the exception block
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
try {
sdf.setLenient(true);
Date date = sdf.parse("1/33/1999");
System.out.println("DateFormat is OK");
sdf.setLenient(false);
date = sdf.parse("1/33/1999");
} catch (ParseException ex) {
ex.printStackTrace();
if (!sdf.isLenient()) {
System.out.println("Invalid date");
} else {
System.out.println("Invalid date pattern");
}
}
format given is wrong.
By that if you mean that the format is invalid, then that throws IllegalArgumentException, see here.
But you should not have to check that, the pattern you supply is determined at compile time and you should be able to ensure that it is valid; the check should be required only if the pattern is not known at compile time.
I read the doc and see that different exceptions are thrown in the two cases, so you can differentiate based on the exception class:
try {
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
sdf.setLenient(false);
Date date = sdf.parse("1/14/1999");
} catch (IllegalArgumentException ex) {
// format exception
} catch (ParseException ex) {
// parse exception
}
Kindly have a look at these Methods .I am not good at exceptions but maybe it gives you some help.
try{
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
sdf.setLenient(false);
Date date = sdf.parse("1/14/1999");
}catch(ParseException ex){
ex.printStackTrace();
System.out.println(ex.toString());//get cause and message ,localized details
System.out.println(ex.etErrorOffset()); //get position of error
}
I have a set of strings. This strings are actually "year"s. for example: "1967","1872","2012",...
I want to create a SimpleDate instance from each of these. Is there a way to create a SimpleDate from a year String?
I have a rather hacky solution for this, which is attaching "-00-00" to my year strings and parsing it into a a SimpleDate. I need a more non-hacky way of doing this.
Thx
I am not sure but maybe you asking about something like this
SimpleDateFormat sdf=new SimpleDateFormat();
sdf.applyPattern("YYYY");
Date d=null;
try {
d = sdf.parse("1999");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(d);
Calendar calendar = Calendar.getInstance();
calendar.set(Integer.parseInt(year), 0, 1);
calendar.getTime();
You could use SimpleDateFormat.
String str_date="1997";
Date date;
try {
DateFormat formatter = new SimpleDateFormat("yyyy");
date = (Date)formatter.parse(str_date);
} catch (ParseException e) {
// handle exception (date will be null)
}
I get this date as a string from SOAP message
"2009-12-02T12:58:38.415+01:00"
Most i could i could identify and vary on subject was
to play with this format yyyy-MM-dd ? hh:mm:ss.????
I tried different combinations using SSS T z Z instead of '?"
DateFormat df = new SimpleDateFormat("... various formats ...");
System.out.println(df.parse("2009-12-02T12:58:38.415+01:00"));
but no success.
Any idea ?
Thanks
you have to change the timezone part. try this:
String a = "2009-12-02T12:58:38.415+01:00";
a = a.replaceFirst(":(?=\\d+$)", "");
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
System.out.println(df.parse(a));
I don't think this is possible using the standard Java date formatting.
Using joda-time this can be done using the following code:
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
.appendYear(4, 4).appendLiteral('-').appendMonthOfYear(2).appendLiteral('-').appendDayOfMonth(2)
.appendLiteral('T')
.appendHourOfDay(2).appendLiteral(':').appendMinuteOfHour(2).appendLiteral(':').appendSecondOfMinute(2)
.appendLiteral('.').appendMillisOfSecond(3).appendTimeZoneOffset(null, true, 2, 2);
DateTimeFormatter dateTimeParser = b.toFormatter();
System.out.println(dateTimeParser.parseDateTime("2009-12-02T12:58:38.415+01:00"));
Try with the following.
String date = "2009-12-02T12:58:38.415+01:00";
int lastIndexOf = date.lastIndexOf(":");
if(lastIndexOf>=0){
date = date.substring(0,lastIndexOf)+date.substring(lastIndexOf+1);
}
System.out.println("~~~~~~date~~~~~"+date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSZ");
try {
sdf.parse(date);
System.out.println("....date..."+date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}