SimpleDateFormat parsing returns null - java

I have a date value of the type "2013-03-28T15:16:58.000Z". I want to convert it to "dd-MMM-yyyy" format. For that, I have used the following code:
public static String getTime(String time)
{
try
{
String tim = time.replace("T", " ");
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", Locale.US);
SimpleDateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
return df2.format(df1.parse(tim));
}
catch (ParseException e)
{
return null;
}
}
I got this solution from a variety of posts here in StackOverflow. But this code still returns null. Can anyone tell me why?

The null value is being returned from exception block due the first SimpleDateFormat returning null as a result of an invalid date format.
The Zpattern is used to denote timezone patterns. To accept a literal Z character, you need to surround the character with single quotes.
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'Z'", Locale.US);
Also, you can do the same with the T character if you don't wish to do a manual replace:
Instead of
String tim = time.replace("T", " "); // remove
just use time and use:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);

It is returning null because it is catching a ParseException and you are telling it to return null. You should be at least print out the stacktrace and that should tell you why you are getting the ParseException.

It's throwing a ParseException parsing the string 2013-03-28 15:16:58.000Z.
Try getting rid of the Z [like you did with the T] and using a SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)

Related

How to get an exception or any sort of feedback while parsing incorrect String to Date

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);

NumberFormatException Error

Hi i get the following error:
2014-09-26T14:17:40.779-0300|Grave: 'java.lang.NumberFormatException' recebido ao invocar escuta de a��o '#{comentario.cancelarAtendimento}' para o componente 'j_idt140'
2014-09-26T14:17:40.780-0300|Grave: java.lang.NumberFormatException: For input string: ""
i created this formatter :
DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("pt", "BR"));
and i want to retrive the date from the session in this way :
if (sessao.getAttribute("dataInicial") != null)
{
dataInicial = (String) sessao.getAttribute("dataInicial");
dataIni = new java.sql.Date(formatter.parse(dataInicial).getTime());
}
then i pass the dataIni here
ocorrencias = cadastradorOcorrecia.pesquisarAvancada(usuario.getCodigo(), Integer.parseInt(pesqCodigo), pesquisaCliente, pesquisaStatus, pesquisaDepartamento, pesquisaSolicitante, pesquisaUltimoAtend, pesquisaSistema, dataIni, dataFi, pesquisaCriador,Integer.parseInt(pesquisaProduto),Integer.parseInt(pesquisaModulo));
here i get the numberFormatException ---> Can anyone have an idea of what i´m doing wrong?
Thanks in advance
and then it goes to the dao instance for retrive the information with the database.
The Integer.parseInt throws NumberFormatException if it cannot convert a string into integer. In your case I would check the values of pesqCodigo, pesquisaProduto & pesquisaModulo.
JavaDoc for Integer.parseInt(String s)
Examples
Integer.parseInt(" 234"); ---> Throws NumberFormatException as it has space
Integer.parseInt(""); ---> Throws NumberFormatException as it is not parseable for an integer
Integer.parseInt(null); ---> Throws NumberFormatException and not npe
Integer.parseInt(" 234 ".trim()); ---> Doesnt throw NumberFormatException as it trims before trying to parse it.
Edit:
It is not surprising that it does not work. This would probably work better:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Then to print with your required format you need a second SimpleDateFormat:
Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));
Notes:
you should include the locale as if your locale is not English, the day name might not be recognised
IST is ambiguous and can lead to problems so you should use the proper time zone name if possible in your input.
At least one of pesqCodigo, pesquisaProduto or pesquisaModulo is a String that does not represent a number.
I think there is no relation with dataInicial, as a DateFormat shouldn't throw a NumberFormatException. The Integer.parseInt() methods can throw this Exception, so just have a look at the use of that function.

Date Validation in Jtextfield for the specified Format

I need to Validate Date in a specified format where both the inputs will be given only in the runtime in JTextfield and will be changing dynamically. Below is the code I have tried:
Date dd = new Date();
DateFormat df = new SimpleDateFormat(Date_format_text.getText());
try {
df.setLenient(false);
Date d1 = df.parse(Lower_date_text.getText());
System.out.println("Correct");
validator_LD.setVisible(false);
} catch (ParseException p) {
validator_LD.setText("*Not in mentioned Format '" + df.format(dd) + "'");
validator_LD.setVisible(true);
System.out.println("Wrong");
}
The above is.. i get the Date specified and the format specified from the text field and try to parse according to the specified format. If it doesn't match it will throw exception.
But this is not working properly in some cases :
If I give the Date 02/01/20'and the Format - dd/MM/YYYY where it should throw an exception since I have given the year as 20 and the format is 'YYYY' but i doesn't give exception.
Kindly help me.. Thanks in advance
First, you may want to take a look at How to Use the Focus Subsystem, paying attention to Validating Input which might help.
Second, as pointed out by #eatSleepCode, you're not actually parsing the text of the field, but are simply formatting an existing Date, so it will never throw an exception...
simple_format = new SimpleDateFormat(Date_format_text.getText());
// This is simply formatting the dates...
String ss = simple_format.format(dates);
Instead, you need to use something more like...
String test = "02/01/20";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
try {
Date date = sdf.parse(test);
if (!sdf.format(date).equals(test)) {
throw new ParseException(test + " is not a valid format for " + format, 0);
}
} catch (ParseException ex) {
ex.printStackTrace();
}
What this does, is test's the parser capabilities of the formatter, but also checks the input against what the resulting parsed Date would be formatted to, if these don't match it throws a ParseException. This is the closes I've been able to get to a strict parser...
Also, YYYY used to represent the week in year, not the year...

Java SimpleDateFormat is parsing wrong dates

I have written the following code snippet:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
currentString = currentString.trim();
try{
Date date = sdf.parse(currentString);
} catch (java.text.ParseException e) {
return "";
}
I am expecting it to parse the date in format yyyy-MM-dd ie. it should parse date like 2013-10-28.
Though it is working fine, it is also parsing wrong inputs like 2013-10-28aaab. Ideally it should throw the exception when such kind of illegal date is given.
How can I restrict such illegal Date Patterns?
use a regex to match the input
something like
"/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/"
Just check the String length. BTW, you should set lenient to true, otherwise non valid dates (2013-02-31) will be allowed.

java : java.text.ParseException: Unparseable date

I am reciving a input in this format 2012-01-13T00:00:00.000-05:00 and which i need to convert this into yyyyMMdd Format .
I have also set the SimpleDateFormat.setLenient(false);
This is my coding for parsing the Date
public static String getparsedDate(String date) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
sdf.setLenient(false);
String s1 = date;
String s2 = null;
Date d;
try {
d = sdf.parse(s1);
s2 = (new SimpleDateFormat("yyyyMMdd")).format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return s2;
}
But i am getting a Exception at
java.text.ParseException: Unparseable date: "201201"
at java.text.DateFormat.parse(Unknown Source)
Could anybody please let me know , what might be the issue ?
You are missing the timezone in your format string. If you check the argument, it is finishing with -05:00 and you are also using Lenient==false.
Unfortunately, the time zone formats available to SimpleDateFormat are not ISO8601 compliant. SimpleDateFormat understands time zone strings like "GMT+01:00" or "+0100", the latter according to RFC822. Therefore using SimpleDateFormat does not seem as an option in your case (since you use UTC−05:00 as timezone).
Instead of SimpleDateFormat you need to use JodaTime for that type of date format.

Categories

Resources