java.lang.NumberFormatException: For input string: "02/10/2015" - java

i try to convert date like 02/10/2015 to string
i am trying but i get error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "02/10/2015"
this is my code
private Crosshair xCrosshair;
long time = ds.getX(xy.getSeriesIndex(), xy.getItem()).longValue();
DecimalFormat dfT = new DecimalFormat("00");
GregorianCalendar gc = new GregorianCalendar();
long lDte = (long)time;
Date dtXX = new Date(lDte);
gc.setTime(dtXX);
String sDD = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.DAY_OF_MONTH))));
String sMM = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.MONTH)+1)));
String sYY = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.YEAR))));
String dateString = sDD +"/"+ sMM +"/"+ sYY;
this.xCrosshair.setValue(Double.parseDouble(dateString));

This row
this.xCrosshair.setValue(Double.parseDouble(dateString));
try to convert a String that is a date to a Double (that is not a date)

You code cannot work:
String dateString = sDD +"/"+ sMM +"/"+ sYY;
this.xCrosshair.setValue(Double.parseDouble(dateString));
dateString will always have a / so it never will be correctly parsed.
For this use SimpleDateFormat:
DateFormat dt = new SimpleDateFormat("dd/MM/yyy");
long d = dt.parse(dateString).getTime();

As already pointed out, the error is happening because you are trying to parse a string that contains invalid characters, see:
http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)
If you want to parse the date as a double, then one possible solution would be:
String doubleString = sDD + sMM + sYY; // Simply leave the slashes out, but is this really what you're after?
this.xCrosshair.setValue(Double.parseDouble(doubleString));

Related

Convert part of string to java.util.Date

I am posting DateTime as JSON and it becomes "/Date(1512839439513)/"
i simply want to convert
"/Date(1512839439513)/" to java.util.Date
I have tried this
String date = finalObject.getString("DateCreated");
String datereip = date.replaceAll("\\D+","");
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);
But did not worked...
The way you extract the milliseconds from the string seems to be the problem.
You can try this to extract needed data from the string:
String date = finalObject.getString("DateCreated");
String temp = date.substring(date.indexOf("(") + 1);
String datereip = date.substring(0, date.indexOf(")"));
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);
This assumes that the date string will have only one pair of parenthesis. Also, there are better ways to extract string between 2 chars with Java but that is a topic of another question.

Parse a date from a string

I have String like this:
String strDateTimeStamp = "2016-02-29 18:31:51";
Now I would like to extract it to get result in a below format:
String strYear = "2016";
String strMonth = "02";
String strDate = "29";
String strHour = "18";
String strMinute = "31";
String strSecond = "51";
If you are working with dates you should consider using Calendar :
String strDateTimeStamp = "2016-02-29 18:31:51";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(strDateTimeStamp);
Calendar cal = new Calendar.Builder().setInstant(date).build();
String strYear = Integer.toString(cal.get(Calendar.YEAR));
// Calendar MONTH is starting from 0 we need to add 1
String strMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
String strDate = Integer.toString(cal.get(Calendar.DATE));
String strHour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
String strMinute = Integer.toString(cal.get(Calendar.MINUTE));
String strSecond = Integer.toString(cal.get(Calendar.SECOND));
All of the Answers using java.util.Date and java.text.DateFormat/.SimpleDateFormat are outmoded. Those old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
java.time
The java.time framework is built into Java 8 and later. A vast improvement over the old date-time classes.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
First, replace the SPACE in the middle of your input string with a T to conform with the ISO 8601 standard. These standard formats are used by default in the java.time classes when parsing/generating strings.
String input = "2016-02-29 18:31:51".replace( " " , "T" );
Parse as a LocalDateTime. The “Local” means not associated with any time zone. So this is not an actual moment on the timeline. But apparently not an issue in the context of this Question.
LocalDateTime ldt = LocalDateTime.parse( input );
Now you can ask for your various pieces as needed by calling the various getter methods. These methods return an int primitive which you can, of course, convert to String values.
getYear
getMonthValue (or getMonth for Month enum))
getDayOfMonth (and getDayOfWeek for DayOfWeek enum)
getHour
getMinute
getSecond
getNano (the fraction of a second)
Try This..
String CurrentString = "2016-02-29 18:31:51";
String[] separated = CurrentString.split(" ");
String date = separated[0];
String time = separated[1];
String[] separated_date = date.split("-");
String[] separated_time = time.split(":");
String strYear = separated_date[0];
String strMonth = separated_date[1];
String strDate = separated_date[2];
String strHour = separated_time[0];
String strMinute = separated_time[1];
String strSecond = separated_time[2];
You can do like this by splitting your String
String[] splittedString = strDateTimeStamp.split("-|:|\\s");
String strYear = splittedString[0];
String strMonth = splittedString[1];
String strDate = splittedString[2];
String strHour = splittedString[3];
String strMinute = splittedString[4];
String strSecond = splittedString[5];
First split string using split(" ") on the basis of space ..it will give you a array of string of length 2 . which contains (2016-03-04) and (16:32:33) . Then split both string againg using split("-") and split(":") reapectively . you will get your answer. Please try code at your own may better to you.
I suggest to use regex with a pattern like "[- :]"
Example:
public static void main(String[] args) {
String strDateTimeStamp = "2016-02-29 18:31:51";
String[] solution = strDateTimeStamp.split("[- :]");
for (int i = 0; i < solution.length; i++) {
System.out.println(solution[i]);
}
}
this will generate an array with all the elements you need
String strDateTimeStamp = "2016-02-29 18:31:51";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(strDateTimeStamp);
Calendar cal = new Calendar.Builder().setInstant(date).build();
String strYear = Integer.toString(cal.get(Calendar.YEAR));
// Calendar MONTH is starting from 0 we need to add 1
String strMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
String strDate = Integer.toString(cal.get(Calendar.DATE));
String strHour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
String strMinute = Integer.toString(cal.get(Calendar.MINUTE));
String strSecond = Integer.toString(cal.get(Calendar.SECOND));

Cast String Date to new format Java

I am trying to cast a date format which is string resultset from database to a standard format, but using simpledateformat gives following error:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at CopyEJ.CopyEJ.main(CopyEJ.java:113)
RROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]
With De-bug I found out variable time_stmp has value "2013-04-19 17:29:06" I want to cast to this:
yyyyMMddhhmmss
Here's code:
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
ResultSet rs_dt = cmd1.executeQuery(dt);
String time_stmp = null;
while (rs_dt.next())
{
time_stmp = rs_dt.getString(1);
}
StringBuilder ts = new StringBuilder( df.format( time_stmp ) );
What is the best way to achieve this?
Your Simple DateFormat has the wrong datepattern. You have to parse it to date with the pattern of you DB, then parse it back to String.
Try it this way:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ResultSet rs_dt = cmd1.executeQuery(dt);
String time_stmp = null;
while (rs_dt.next())
{
time_stmp = rs_dt.getString(1);
}
Date d = null;
try {
Date d = df.parse(time_stmp);
} catch (ParseException ex) {
Logger.getLogger(Prime.class.getName()).log(Level.SEVERE, null, ex);
}
SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddhhmmss");
StringBuilder ts = new StringBuilder( df2.format(d) );
By the way:
If you want your output to be in 24h-Format, then you have to use the pattern yyyyMMddHHmmss
The problem is, format of the date retrieved from DB is yyyy-dd-MM HH:mm:ss and you are trying to parse it with the format yyyyMMddhhmmss
You can do something like this
String date = "2013-04-19 17:29:06";
Date d = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").parse(date);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMddhhmmss");
System.out.println(outputFormat.format(d));
You need to use DateFormat.parse() here since the argument is of type String. DateFormat.format() on the other hand is used to format Date objects as String.
StringBuilder ts = new StringBuilder(df.format(df.parse(time_stmp)));
Also, it's recommended to save date/time data as a TimeStamp in database instead of a String.
Like it was mention you need to use
SimpleDateFormat.parse()
Also if your string is in the form
`2013-04-19 17:29:06`
You will want to construct your SimpleDateFormat for reading in like this
`yyyy-MM-dd HH:mm:ss` //make sure you use uppercase H for 24 hour times
Use SimpleDateFormat.parse() to convert a String to a Date.
Use SimpleDateFormat.format() to convert a Date to a String.
All together now:
SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat stdFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String s = stdFormat.format(dbFormat.parse(input));
You can modify the formats to suit your needs.
Hi you can use below code to format date as of your choice (Ex: yyyy-MM-dd HH:mm:ss)
Calendar calendar = Calendar.getInstance();
Date calDate = calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Calendar Date: " + calDate);
System.out.println("Your Choice Date format (yyyy-MM-dd HH:mm:ss): "+dateFormat.format(calDate));
This will work
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd hhhh:mm:ss");
String time_stmp ="2013-04-19 17:29:06";
Date date=df.parse(time_stmp);
StringBuilder ts = new StringBuilder( df.format( date ) );
System.out.println(ts);

limiting the length of a string

I have a string that says 15:00:00 how can I limit the length of the string so it says 15:00 ?
For dates
Date date = new Date();
SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
sd.format(date); //will return formatted date
Try this,
String time = "15:00:00";
time = time.subString(0,time.lastIndexOf(":"));
try this:
String time = "15:00:00";
String str =time.substring(0,result.length() - 3);

Date time object from webservice showing on Android textview with pattern?

Hi I have web service that return a date object like this as a return of the Json
"/Date(922312800000+0200)/"
However i need to show it on the textview in this pattern
"19.12.2011 16:15"
how can I convert that return to this pattern ?
Edit : Here is my code still giving java.lang.IllegalArgumentException
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateText = date.format(tempEntry.getCreatedDate());
Edit : Here is the code that work for me
String dateText = tempEntry.getCreatedDate();
String dateString = dateText.replace("/Date(", "").replace(")/", "");
String[] dateParts = dateString.split("[+-]");
Date dateFormat = new Date(Long.parseLong(dateParts[0]))
It appears to me that your Date is given in milliseconds from 1970, so, something like that:
// remove the unneeded information
String date = date.replace("/Date(", "").replace(")/");
String[] dateParts = date.split("[+-]")
//get the date represented by the given millis
Calendar c = Calendar.getInstance();
c.setTime(Long.parseLong(dateParts[0]);
// proceed with formatting to the desired date format.
You need to use: DateFormat.
Simple example:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
textView.setText("Today : " + today);

Categories