Converting string to util date
I have a method to define if a string value can be converted into date.
When I pass "20080815" value as a parameter it works fine. But when I pass "20082415" value it also converts the value to a date where the value should not be converted to date. At least I expect so. It should throw an exception because month can not be 24.
Why an how could it be? And is there another way to solve the situation?
public static int ToDate(String p_value) {
try {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
date_val = df.parse(p_value);
return 1;
catch(Exception e) {
return -1;
}Edited by: kalyon on Sep 4, 2008 3:50 AM
Edited by: kalyon on Sep 4, 2008 3:50 AM
df.setLenient(false);read the API docs.
Similar Messages
-
Cannot convert from java.util.Date to java.sql.Date
In the below code am trying to get the current date and 60 days prior date:
Date todayDate;
Date Sixtydaysprior;
String DATE_FORMAT = "MM/dd/yy";
DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar cal = Calendar.getInstance();
todayDate = sdf.parse(sdf.format(cal.getTime()));
cal.add(Calendar.DATE, -60);
Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
<%@page
import="java.util.Calendar,
java.text.SimpleDateFormat,
java.text.ParseException,
java.util.*"
%>Shows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
Thanks.
Edited by: MiltonDetroja on May 22, 2009 11:03 AMShows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
java.util.Date today = new java.util.Date();
long t = today.getTime();
java.sql.Date dt = new java.sql.Date(t); -
Gurus,
It would be highly appreciable if you could help me in knowing how to convert a string to date in obiee. I know we need to use CAST function. I don't have enough material to figure it out myself.
Awaiting a reply.
Thanks.Nico - Thanks for the link, this is very helpful. Please tell me what's wrong in the following code. Am enlcosing the code and the error.
Code 1 :
CAST(CAST('31-OCT-'||CAST(YEAR("Dim - MBS Loan"."CLOSING DATE") AS CHAR) AS CHAR) AS DATE)
Error 1:
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 25137, message: ORA-25137: Data value out of range at OCI call OCIStmtExecute: select distinct D1.c1 as c1, D1.c2 as c2, D1.c3 as c3,
Code 2 :
CAST('31-OCT-'||SUBSTRING(CAST(YEAR("Dim - MBS Loan"."CLOSING DATE") AS CHAR),3,2) AS DATE)
Error 2:
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1840, message: ORA-01840: input value not long enough for date format at OCI call OCIStmtExecute: select distinct D1.c1 as c1, D1.c2 as -
hi all,
i have a date in string format Tue, 06 Feb 2007 12:38:17 GMT
How do i convert it to sql datetime.
Date date = new Date("Tue, 06 Feb 2007 12:38:17 GMT");// creating date
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");// format definition
java.sql.Time pubDate = java.sql.Time.valueOf(sdf.format(date));
System.out.println(pubDate);This code gives me java.lang.NumberFormatException.
Thanks in advance.......
VikraMis "EEE d MMM yyyy HH:mm:ss Z" your default data format
if not your first constructor will not parse date properly so your date object contains invalid date, when you try to format it it throws exception.
check it
sudhir nimavat -
How to convert string value to date
hi,
in my application user enters the date in dd/MM/yyyy formatt..before submtiing to some external server i haveto formatt it to MM/dd/yyyy format bcos it accepts olny this formatt.when i retrieve the string date in my jsp using Sring date = req.getParameter();
i want to convert this date to MM/dd/yyyyy formatt.
Regards,Sring date = req.getParameter();
string formatted = date.substring(0,3) + "/" + date.substring....
? -
Convert string to fomated date
I have a string type "dd/mm/yyyy", how can i convert it to "MMMddyyyy hh::mm:ss AM/PM" date format ??
Calendar cal0 = Calendar.getInstance(); // today's date
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMddyyyy hh::mm:ss AM/PM");
cal0.add(Calendar.DATE,-0);
Calendar calx=cal0.getInstance();
String date0 = dateFormat.format(cal0.getTime());
System.out.println("Date "+date0);
use this,.
if there is any problem write it again,
bye,
Samir -
Cannot find symbl method update Date(int,java.util.Date)
I get following error
cannot find symbl method update Date(int,java.util.Date) on compling class called GuestDataBean at line ( rowSet.updateDate( 4, guest.getDate() ); ).
GustBean.java. I need help on why I get it.
// JavaBean to store data for a guest in the guest book.
package com.deitel.jhtp6.jsp.beans;
import java.util.*;
public class GuestBean
private String firstName;
private String lastName;
private String email;
private Date date;
private String message;
//Constructors
public GuestBean(){
public GuestBean(String firstname, String lastname, String email,Date date,String message){
this.firstName=firstname;
this.lastName=lastName;
this.email=email;
this.date=date;
this.message=message;
// set the guest's first name
public void setFirstName( String name )
firstName = name;
} // end method setFirstName
// get the guest's first name
public String getFirstName()
return firstName;
} // end method getFirstName
// set the guest's last name
public void setLastName( String name )
lastName = name;
} // end method setLastName
// get the guest's last name
public String getLastName()
return lastName;
} // end method getLastName
// set the guest's email address
public void setEmail( String address )
email = address;
} // end method setEmail
// get the guest's email address
public String getEmail()
return email;
} // end method getEmail
public void setMessage( String mess)
message = mess;
} // end method setEmail
// get the guest's email address
public String getMessage()
return message;
} // end method getEmail
public void setDate( Date dat )
date = dat;
} // end method setEmail
// get the guest's email address
public Date getDate()
return date;
} // end method getEmail
} // end class GuestBean
GuestDataBean.java/**
* @(#)GuestDataBean.java
* @author
* @version 1.00 2008/7/18
// Class GuestDataBean makes a database connection and supports
// inserting and retrieving data from the database.
package com.deitel.jhtp6.jsp.beans;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import java.util.ArrayList;
import com.sun.rowset.CachedRowSetImpl; // CachedRowSet implementation
import java.sql.*;
public class GuestDataBean
private CachedRowSet rowSet;
// construct TitlesBean object
public GuestDataBean() throws Exception
// load the MySQL driver
Class.forName( "org.gjt.mm.mysql.Driver" );
// specify properties of CachedRowSet
rowSet = new CachedRowSetImpl();
rowSet.setUrl( "jdbc:mysql://localhost:3306/virsarmedia" );
rowSet.setUsername( "root" );
rowSet.setPassword( "" );
// obtain list of titles
rowSet.setCommand(
"SELECT firstName, lastName, email,date,message FROM guest" );
rowSet.execute();
} // end GuestDataBean constructor
// return an ArrayList of GuestBeans
public ArrayList< GuestBean > getGuestList() throws SQLException
ArrayList< GuestBean > guestList = new ArrayList< GuestBean >();
rowSet.beforeFirst(); // move cursor before the first row
// get row data
while ( rowSet.next() )
GuestBean guest = new GuestBean();
guest.setFirstName( rowSet.getString( 1 ) );
guest.setLastName( rowSet.getString( 2 ) );
guest.setEmail( rowSet.getString( 3 ) );
guest.setDate( rowSet.getDate( 4 ) );
guest.setMessage( rowSet.getString( 5 ) );
guestList.add( guest );
} // end while
return guestList;
} // end method getGuestList
// insert a guest in guestbook database
public void addGuest( GuestBean guest ) throws SQLException
rowSet.moveToInsertRow(); // move cursor to the insert row
// update the three columns of the insert row
rowSet.updateString( 1, guest.getFirstName() );
rowSet.updateString( 2, guest.getLastName() );
rowSet.updateString( 3, guest.getEmail() );
rowSet.updateDate( 4, guest.getDate() );
rowSet.updateString( 5, guest.getMessage() );
rowSet.insertRow(); // insert row to rowSet
rowSet.moveToCurrentRow(); // move cursor to the current row
rowSet.commit(); // propagate changes to database
} // end method addGuest
} // end class GuestDataBeanThis isn't a JSP question, it better belongs in the JavaProgramming, or JDBC forums.
But the problem is because the updateDate method uses a java.sql.Date object and you are giving it a java.util.Date object. You have to convert from java.util.Date to java.sql.Date. See: [the api for java.sql.Date|http://java.sun.com/javase/6/docs/api/java/sql/Date.html] .
Edited by: stevejluke on Jul 21, 2008 5:43 PM -
I am coding a hoilday booking system using JSP to interact with a SQL Server database. On my JSP form which retrieves the information I have a little javascript pop-up date selector which appears to be returning a Timestamp value although the string value is visable in the entry field. Can I pass this to a javabean as a Timestamp, so far I have only passed strings? Also I then have to enter it in the database and so will need to convert it to an sql date type but I dont know which one is best. Previous to using the Timestamp returning calendar I was just entering text and parsing it to a util.Date in the bean and then converting that to an sql.Date for entry in the database. That worked fine but I want to use the pop-up any ideas? Also my bean won't compile if I declare java.util.Timestamp t;(cannot resolve symbol Timestamp !) even though I have imported util.
First of all, java.util.Timestamp does not exist. You probably need java.sql.Timestamp.
java.sql.Date and java.sql.Timestamp inherit from java.util.Date. So converting from java.sql.Date or java.sql.Timestamp to java.util.Date is easy, you don't have to do anything.
To convert a java.util.Date to a java.sql.Timestamp, do something like this:
import java.sql.Timestamp;
import java.util.Date;
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());Jesper -
Convert string to floating-point
Hi all,
..very basic question, but I tryed it for hours and only received short-dumps
<b>How can I convert a string into a floating-point number?</b>
Kind regards,
Stefanhi
try this
to convert string to float.
data : a type f,
s type string value '1.023'.
a = s.
write :/ a.
to convert float to string.
data : a type f value '1.023',
s type string.
s = a.
write : s. -
Default java.util.Date Patter
Hello,
I tried to parse the default Date output String java.util.Date.toString()
"Fri Jan 01 00:00:00 CET 2049" But this patter don't work "E MMM dd HH:mm:ss Z" can anybody tell me what patter the Date Object use? In the API I found no informationen.
String body = "Fri Jan 01 00:00:00 CET 2049";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z");
Date date = (Date)formatter.parse(body);Thanks for helpYou can use SimpleDateFormat API for that. You should use the format() method instead of parse() method.
Date today = new Date();
String humanReadableDateFormat = new SimpleDateFormat("yyyy/MM/dd").format(today);For more patterns, just read the java.text.SimpleDateFormat API documentation. -
Convert String to Date and Format the Date Expression in SSRS
Hi,
I have a parameter used to select a month and year string that looks like: jun-2013
I can convert it to a date, but what I want to do is, when a user selects a particular month-year (let's say "jun-2013")
I populate one text box with the date the user selected , and (the challenge Im having is) I want to populate a text box next to the first text box with the month-year 2 months ahead. So if the user selects
jun-2013 textbox A will show jun-2013
and textbox B will show aug-2013..
I have tried:
=Format(Format(CDate(Parameters!month.Value ),
"MM-YYYY" )+ 2 ) -- But this gives an error
This returns the month in number format like "8" for august...
=Format(Format(CDate(Parameters!month.Value ),
"MM" )+ 2 )
What is the proper syntax to give me the result in this format = "aug-2013" ???
Thanks in advance.
MC
M CollierYou can convert a string that represents a date to a date object using the util.scand JavaScript method, and then format a date object to a string representation using the util.printd method. For more information, see:
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.1254.html
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.1251.html
In your case, the code would be something like:
var sDate = "2013-01-10";
// Convert string to date
var oDate = util.scand("yyyy-mm-dd", sDate);
// Convert date to new string
var sDate2 = util.printd("mm/dd/yyyy", oDate);
// Set a field value
getField("date2").value = sDate2;
The exact code you'd use depends on where you place the script and where you're getting the original date string, but this should get you started. -
How to convert String (dd-MMM-yyyy) to oracle.jbo.domain.Date
Hi
Could you please tell how do I convert String of date in format dd-MM-yyyy to ADF date? Please show me some sample.
Thankshttp://javaalmanac.com/egs/java.text/FormatDateDef.html
Once you have a java.util.Date you can convert it to oracle.jbo.domain.Date. (see http://www.fifkredit.com/bc4jdoc/rt/oracle/jbo/domain/Date.html) -
How to convert string yyyy-mm-dd to date dd/mm/yyyy
Hi Experts,
I am getting date in the form of string 2007-06-30 from R/3. How I can convert this string into a date in the form 30/06/2007. I have to use java.sql.Date.
Following code is not working. As for executing the following code, I have to use java.util.date. I can not use java.util.date as the Web Dynpro program uses java.sql.Date.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yyyy");
Date d = null;
d = sdf1.parse(wdContext.currentContextElement().getDateClicked());
Regards,
GaryHi,
If I understood you right you need this date typed as a java.sql.Date?
String ds=wdContext.currentContextElement().getDateClicked();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date sd = new java.sql.Date(sdf.parse(ds).getTime());
Four remarks:
We "transport" the Date from java.util.Date to java.sql.Date as milliseconds since January 1, 1970, 00:00:00 GMT. See contract of java.sql.Date.
You used dd/mm/yyyy instead of dd/MM/yyyy, but mm are the minutes and not the months, see the contract of [SimpleDateFormat|http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html] (JSE 1.4) .
You do not set the time zone for DateFormat, so you use TimeZone.getDefault(). This is your JVM's default time zone and depends (if you did not change it) on your systems time zone. F.e. I live in Germany, the time zone of my system is currently MEZ (which is UTC+1) since we left the daylight saving time zone last sunday. Since you only parse the date and not the time zone f.e., you expect the date (the string) to be in your default time zone. If this is not the case, you have to set the time zone to the time zone you expect the date to be in (f.e. sdf1.setTimeZone(TimeZone.getTimeZone("UTC"));) before parsing the date. This might seem marginal in your case, but may produce unexpected results with date comparisons and date parsings around the day change.
SimpleDateFormat is not thread-safe, so please do not cache it! This is not mentioned in the Javadoc of JSE 1.4, but can be looked up at [Sun's bug database|http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=96669461418011fffffffffb70dd6b6e88eb5?bug_id=4264153]. If you are not satisfied with the standard Date & Time handling (f.e. performance reasons) you might want to consider an alternative like [Joda Time|http://joda-time.sourceforge.net/index.html] which is published under [ASF 2.0 license|http://joda-time.sourceforge.net/license.html]
Best regards,
Fabian -
Need info on SimpleDateFormat, Converting String to Date
I'm a newbie and doing a conversion of a string to a date and it's adding a little less than 11 minutes. I know I'm missing something really simple but as I read it I ought to be able to convert "20030125 084539.637696" to Sat Jan 25 08:45:39 not 8:56! Also, for the time being I'm ignoring the zulu 'Z' because I can't find a pattern that'll take it.
System.out.println("INFO:MetadataExtractorBean::filestarttime:" + filestarttime);
filestarttime = filestarttime.replace("Z","");
System.out.println("after filestarttime.replace(Z,null) filestarttime:" + filestarttime);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd hhmmss.SSSSSS");
Date convertedDate = dateFormat.parse(filestarttime);
System.out.println("after dateFormat.parse(filestarttime) convertedDate:" + convertedDate);
INFO:MetadataExtractorBean::filestarttime:20030125 084539.637696Z
after filestarttime.replace(Z,null) filestarttime:20030125 084539.637696
after dateFormat.parse(filestarttime) convertedDate:Sat Jan 25 08:56:16 EST 2003
Can someone help me with a) why it doesn't remain 8:45, and b) how to modify the pattern to be able to parse a zulu date. Thanks in advance.import java.text.*;
public class ParsingExample {
public static void main(String[] args) throws ParseException {
String s = "20030125 084539.637";
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd HHmmss.SSS");
System.out.println(f.parse(s));
}Your round up was because ".637696" was taken to mean 637,696 milliseconds. SimpleDateFormat doesn't have a way to accept microseconds, and anyway, java.util.Date only has millisecond precision. I also changed "hh" to "HH" because I assume this is with a 24 hour clock.
edit: you can tell your date format not to do these roll ups by setting:
f.setLenient(false); -
Converting Java.util date to XML date in format YYYY-MMM-dd
I'm using below code to convert java.util.date to XML date
public static XMLGregorianCalendar toXMLDate(Date dte) {
try {
// this may throw DatatypeConfigurationException
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
GregorianCalendar calendar = new GregorianCalendar();
// reset all fields
calendar.clear();
Calendar parsedCalendar = Calendar.getInstance();
parsedCalendar.setTime(dte);
calendar.set( parsedCalendar.get(Calendar.YEAR ),
parsedCalendar.get(Calendar.MONTH),
parsedCalendar.get(Calendar.DATE ));
XMLGregorianCalendar xmlCalendar = datatypeFactory.newXMLGregorianCalendar( calendar );
xmlCalendar.setTimezone( DatatypeConstants.FIELD_UNDEFINED );
xmlCalendar.setFractionalSecond( null );
return xmlCalendar;
I need to get the date in the format YYYY-MMM-dd, but it returns in a format YYYY-MM-dd. Can anyone tell me how can i change the format? Thanks>
The snippet of ApplicationClient where the assignment took place and the syntax occurred were:
1. DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
2. DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
3. Date date = new Date();
4. CustomerDetail customerDetail = new CustomerDetail();
5. customerDetail.setCollectionDate(dateFormat.format(date)); //got the above syntax error
6. customerDetail.setCollectionTime(timeFormat.format(date)); //got the above syntax error
.....I am running JDK 1.6.0_10, Glassfish v2r2, MySQL 5.0, Netbeans 6.1 on Windows XP platform.The format method returns a String not a Date. Why not just store the Date as is without formatting, and format it when you want to retrieve it from the DB and display it?
m
Maybe you are looking for
-
How to redirect to home page on "Cancel" button click
Hi, I have created a web part for office 365 developed using sandbox solution on Sharepoint foundation 2013. On "Cancel" button click i want to redirect user to another page(Home page) using C# only. i used some methods like Context.Response.Redirec
-
I'd like to share my experiences with BT recently, to see if other customers have had similar struggles: 23rd Oct 2012: Placed an order for a new phoneline connection and broadband. Told the first available Openreach engineer's appointment was for 13
-
Oracle 11gR2 RAC: Running the script root.sh problem
Folks, Hello. I am installing Oracle 11gR2 RAC using 2 Virtual Machines (rac1 and rac2 whose OS are Oracle Linux 5.6) in VMPlayer and according to the tutorial http://appsdbaworkshop.blogspot.com/2011/10/11gr2-rac-on-linux-56-using-vmware.html I have
-
I need to find out how to transfer all my music from my original IPOD nano to my new IPOD nano. I want to keep both and not all of my music was purchased on ITUNES. Please help!
-
I had created a form on table with report. When the user clicks on the link image on the report, it query up the data on the form. It does all of the DML on the form behind the scenes. Now I have to do the same thing, but the form needs to be based o