error on converting string to date in java - java

2014-04-23T18:30:00.000Z need to convert in this format yyyy-MM-dd'T'hh:mm:sszzz in java
I am using this
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.zzzZ");
Date newfromDate = new Date();
try {
//Convert into date
newfromDate = (Date)formatter.parse(fromDate);
// get required Format of date in string format
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:sszzz");
} catch (ParseException e) {
e.printStackTrace();
}
but this is not working
error :- java.text.ParseException: Unparseable date: "2014-03-31T18:30:00.000Z"

try this
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX").parse(s);
or this
javax.xml.bind.DatatypeConverter.parseDateTime("2014-04-23T18:30:00.000Z");
the last version is supposed to be faster (no need to parse pattern) and thread-safe

Related

java.text.ParseException: Unparseable date: "2018-05-23T06:39:37+0000"

I'm trying to create a Date from a String I receive from the server. The String is:
2018-05-23T06:39:37+0000
So the correct format should be:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
Here is my code:
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date parsedDate = simpleDateFormat.parse(createdDate);
createdDate = parsedDate.toString();
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
I don't know if there is any way to do this, because after that I would like to parse again to the next format:
dd/MM/yyyy hh:mm
I've tried to parse the original String using this last format directly but I'm getting the same exception.
Any suggestion?
I see you've solved your own problem with a little help from the comments, however I would suggest you seriously consider LocalDate, as the older Date classes are quite troublesome at times.
In fact, as your incoming value has a TimeZone, you'll need to use ZonedDateTime to parse your input.
String createdDate = "2018-05-23T06:39:37+0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
ZonedDateTime localDate = ZonedDateTime.parse(createdDate, formatter);
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")));
Output:
23/05/2018 06:39
The given input date String format
2018-05-23T06:39:37+0000
is incorrect so that you are getting ParseException since millisecond(SSS) part is missing from your date format yyyy-MM-dd'T'HH:mm:ss.SSSZ
So please try with
2018-05-23T06:39:37.235-0530
so below code should work
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date parsedDate = simpleDateFormat.parse(createdDate);
createdDate = parsedDate.toString();
System.out.println(parsedDate.toString());
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
Ok, the first mistake (as you've pointed) is I didn't have milliseconds on the original String.
After removing "SSS" from the simpleDateFormat it works like a charm. So this is the final code:
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
Date parsedDate = defaultDateFormat.parse(createdDate);
SimpleDateFormat finalDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
createdDate = finalDateFormat.format(parsedDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);

Convert `Java.lang.String` TO `oracle.sql.TIMESTAMPTZ`

I have these following Java.lang.String values that represents String value of TIMESTAMPTZ. I need to convert these Java.lang.String TO oracle.sql.TIMESTAMPTZ.
"2016-04-19 17:34:43.781 Asia/Calcutta",
"2016-04-30 20:05:02.002 8:00",
"2003-11-11 00:22:15.0 -7:00",
"2003-01-01 02:00:00.0 -7:00",
"2007-06-08 15:01:12.288 Asia/Bahrain",
"2016-03-08 17:17:35.301 Asia/Calcutta",
"1994-11-24 11:57:17.303"
I tried it by many ways.
Sample 1:
Tried it by using SimpleDateFormat
String[] timeZoneValues = new String[]{"2016-04-19 17:34:43.781 Asia/Calcutta", "2016-04-30 20:05:02.002 8:00", "2003-11-11 00:22:15.0 -7:00", "2003-01-01 02:00:00.0 -7:00", "2007-06-08 15:01:12.288 Asia/Bahrain", "2016-03-08 17:17:35.301 Asia/Calcutta", "1994-11-24 11:57:17.303"};
for(String timeZoneValue: timeZoneValues){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
try {
simpleDateFormat.parse(timeZoneValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
That thrown an Exception:
java.text.ParseException: Unparseable date: "2016-04-19 17:34:43.781 Asia/Calcutta"
at java.text.DateFormat.parse(DateFormat.java:357)
Sample 2:
Tried it by converting these String values directly into Timestamp or oracle.sql.TIMESTAMPTZ
String parse = "2016-04-19 17:34:43.781 8:00";
try {
Timestamp timestamp = Timestamp.valueOf("2016-04-19 17:34:43.781 8:00");
}catch (Exception ex){
ex.printStackTrace();
}
Exception:
java.lang.NumberFormatException: For input string: "781 8:000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.sql.Timestamp.valueOf(Timestamp.java:253)
Sample 3:
String parse = "2016-04-19 17:34:43.781 Asia/Calcutta";
DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();
DateTime dateTime = dateTimeFormatter.parseDateTime(parse);
Timestamp timeStamp = new Timestamp(dateTime.getMillis());
Exception:
Invalid format: "2016-04-19 17:34:43.781 Asia/Calcutta" is malformed at " 17:34:43.781 Asia/Calcutta"
Sample 4:
try {
TIMESTAMPTZ timestamptz = new TIMESTAMPTZ(connection, (String) colValue);
}catch (Exception ex){
ex.printStackTrace();
}
Exception:
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
at java.sql.Timestamp.valueOf(Timestamp.java:249)
at oracle.sql.TIMESTAMPTZ.toBytes(TIMESTAMPTZ.java:1919)
at oracle.sql.TIMESTAMPTZ.<init>(TIMESTAMPTZ.java:253)
I am trying to insert the TIMESTAMPTZ value into Oracle database using Apache Metamodel and I have Java 1.7 installed on my system.
Your timestamps are not in a standard java parseable formats. So in order to parse them you need to write custom code for handling such formats.
Couple of observations:
Asia/Calcutta is not a valid Parseable TimeZone, hence you need some
mechanism to get corresponding timezone.
8:00 is also not a valid Parseable Timezone in java, hence you need
some mechanism to format it in a valid value +08:00
Keeping above points in mind, following code will do the needful for you.
SimpleDateFormat dateFormatTZGeneral = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
SimpleDateFormat dateFormatTZISO = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
SimpleDateFormat dateFormatWithoutTZ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String[][] zoneStrings = DateFormatSymbols.getInstance().getZoneStrings();
Date date = null;
String[] timeStampSplits = timestamp.split(" ");
if(timeStampSplits.length>2) {
String timezone = timeStampSplits[2];
//First Case Asia/Calcutta
if(Character.isAlphabetic(timezone.charAt(timezone.length()-1))) {
for(String[] zoneString: zoneStrings) {
if(zoneString[0].equalsIgnoreCase(timezone)) {
timeStampSplits[2] = zoneString[2];
break;
}
}
timestamp = createString(timeStampSplits," ");
date = getDate(timestamp, dateFormatTZGeneral);
} else {
//Second Case 8:00
timeStampSplits[2] = formatTimeZone(timeStampSplits[2]);
timestamp = createString(timeStampSplits," ");
date = getDate(timestamp, dateFormatTZISO);
}
} else {
// Third Case without timezone
date = getDate(timestamp, dateFormatWithoutTZ);
}
System.out.println(date);
TIMESTAMPTZ oraTimeStamp = new TIMESTAMPTZ(<connection object>,new java.sql.Timestamp(date.getTime());
Above code uses following utility methods
private static Date getDate(String timestamp, SimpleDateFormat dateFormat) {
Date date = null;
try {
date = dateFormat.parse(timestamp);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
private static String createString(String[] contents, String separator) {
StringBuilder builder = new StringBuilder();
for (String content : contents) {
builder.append(content).append(separator);
}
builder.deleteCharAt(builder.length()-separator.length());
return builder.toString();
}
private static String formatTimeZone(String timeZone) {
String[] timeZoneSplits = timeZone.split(":");
DecimalFormat formatter = new DecimalFormat("+##;-#");
formatter.setMinimumIntegerDigits(2);
timeZoneSplits[0] = formatter.format(Integer.parseInt(timeZoneSplits[0]));
return createString(timeZoneSplits, ":");
}
This code is specifically written to cater your timestamp examples, any deviation might not be handled by this and it will need more customization.
Hope this helps you.
You have to parse the date according to the data coming i.e dynamic. For information about What constant used by android you have to follow the link
and in case of Java you have to follow link
Here is the code snippet of some different format
Sample 1
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzzz");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781 Pacific Standard Time");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
Sample 2
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781 -08:00");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
Sample 3
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
So as per these three set of sample you can parse any type of date time except the one format i.e "2016-04-19 17:34:43.781 Asia/Calcutta" as the time zone Asia/Calcutta or Asia/Bahrain can not get read by android or java. This is the format which gets supported by PHP as per my understanding. SO If you want to parse these type of format then I guess you have to write your custom SimpleDateFormat and have to identify these content and perform the calculation according to your need.
The Timestamp strings are in different format,
Ex-Here SimpleDateFormat uses pattern :
'yyyy-MM-dd HH:mm:ss.SSS XXX'
where X is to represent timezone in [ISO 8601 time zone][1] format.For this
timezone valid Timestamp Strings are (-08; -0800; -08:00).So,'Asia/Kolkata'
will not be parsed for Sample 1.
There are three type of Timezone pattern to be assigned to SimpleDateFormat.
**'Z'** - RFC 822 time zone.
**'z'** - General time zone.
**'X'** - ISO 8601 time zone.
So,either use different SimpleDateFormat's,or convert Timezone of all timestamp into same pattern of timezone and use a single SimpleDateFormat.

How do I convert 09/24/2015 into 20150924?

How can one convert the input date formatted as mm/dd/yyyy into an integer formatted as yyyymmdd.
I tried:
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
String input = "09/25/2015";
String t;
t = ft.format(input);
and
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
String input = "09/25/2015";
String t;
try{
t = ft.parse(input);
}catch (ParseException e){
}
}
Neither of these worked; The first one gave me a runtime error.
Assuming the input date is in type of a String:
String strDate = "09/24/2015";
String[] tok = strDate.split("/");
System.out.println(tok[2] + tok[0] + tok[1]);
You can split them into tokens.
You can do it in two ways: String manipulation, or date parsing and reformatting.
// String substitution using regular expression
System.out.println("09/24/2015".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
// Lenient date reformatting
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("MM/dd/yyyy").parse("09/24/2015")));
String substitution will do nothing for bad formats, and will convert good formats even if date values are bad.
The date reformatting will fail (exception) for bad formats, and will "adjust" bad date values (see below), because it's lenient by default. Change to strict to also fail on bad date values:
// Strict date reformatting
SimpleDateFormat mdy = new SimpleDateFormat("MM/dd/yyyy");
mdy.setLenient(false);
SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
System.out.println(ymd.format(mdy.parse("09/24/2015")));
The above three methods will all print:
20150924
To show the effect of bad date values,a dn with bad formats:
// Showing results with bad date
System.out.println("09/34/2015".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new SimpleDateFormat("MM/dd/yyyy").parse("09/34/2015")));
try { ymd.format(mdy.parse("09/34/2015")); } catch (Exception e) { System.out.println(e); }
// Showing results with bad formats
System.out.println("Hello".replaceFirst("^(\\d{2})/(\\d{2})/(\\d{4})$", "$3$1$2"));
try { new SimpleDateFormat("MM/dd/yyyy").parse("Hello"); } catch (Exception e) { System.out.println(e); }
try { ymd.format(mdy.parse("Hello")); } catch (Exception e) { System.out.println(e); }
Output
20150934
20151004
java.text.ParseException: Unparseable date: "09/34/2015"
Hello
java.text.ParseException: Unparseable date: "Hello"
java.text.ParseException: Unparseable date: "Hello"

Converting String to SQL Date

I am trying to convert the String to java.sql.Date.
This string I am getting from my jsp page using request.getparameter(date); which will return string and now I am trying to convert this String to Java.util.Date and then converting to java.SQL.Date.
For this I am using the below code
DateFormat format=new SimpleDateFormat("MM-dd-yyyy");
java.util.Date parsed = new Date(0);
try {
System.out.println("inside try block");
format.setLenient(false);
parsed = format.parse(dob);
System.out.println("parsed date inside try block"+parsed);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But the statement parsed=format.parse(dob) is not executing.
Try the below code
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Source
After the line parsed = format.parse(dob);
you have to add the below line to convert it to java.sql.date format.
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
If the string is like "12201430" then you have to use formatter like new SimpleDateFormat("MMyyyydd"),same way for other scenarios also else you will get a ParseException.
You can get this done by using this sample code
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
nowdate="12-30-2014"
Date YourResult=sdf.parse(nowdate);
java.sql.Date todayssqldate=new java.sql.Date(YourResult.getTime());

Java Unparseable Date difference in formats

How to differentiate between data-entry being (a) invalid date or (b) invalid format?
I have the following code for handling date inputs from an text file.
public boolean dateIsValid(String date) {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
try {
Date dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
I have everything working as I want it to. The only problem I have is I am unable to differentiate the different parse exceptions thrown. For example:
if String date = 18/10/2012 --> java.text.ParseException: Unparseable date: "18/10/2012"
if String date = 2-12-2001 --> java.text.ParseException: Unparseable date: "2-12-2001"
As you can see, both the wrong formats throw the same error. How can I differentiate them so that I can handle them differently?
EDIT
To be more precise, in case of date 18/10/2012, I should throw an invalid date error and in the case of date 2-12-2001, I need to throw an invalid format exception. I dont need to handle different formats. I just need a way of getting different exceptions for these two different cases.
The issue seems to be at this line
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
For the first error it looks like that the date is coming first and the month later so it should be like
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Second error shows the incorrect format of the date supplied since it is containing - whereas you are expecting the format containing / ie like
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
If you want to handle different formats then try like this:
String[] formatDates= {"MM/DD/yyyy", "dd/MM/yyyy", "MM-dd-yyyy","dd-MM-yyyy"};
Date tryParse(String dateString)
{
for (String formatDate: formatDates)
{
try
{
return new SimpleDateFormat(formatDate).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Unless you write code to parse the date strings yourself, you will not know why the format threw the exception.
I recommend a variation of the R. T. answer above.
Specifically, instead of creating a new formatter every time, create four (in that example) formatters at startup (in the constructor or in a static block).
I would use
public Date dateIfValid(String format, String date) {
DateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
try {
return dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
return null;
}
}
Date mmddyy = dateIfavlid("MM/dd/yy", date.replace("[^0-9]", "/"));
Date ddmmyy = dateIfavlid("dd/MM/yy", date.replace("[^0-9]", "/"));
if (mmddyy != null && ddmmyy == null) {
Note: this can be used to detect ambigous dates such as 01/02/03 which might be 3rd Feb 2001

Categories