Convert from String to Date
Hello,
I have the following string: "Thu Apr 22 00:00:00 IDT 2004"
and I need to convert it to Date object.
I tried to use Date.parse() and Date.valueOf(),
but then I get the IllegalArgumentException.
How can I do this?
Thanks.
split ur string. get year,month,day in int
time in long
now it will work for u
Date d = new Date(int year,int mon,int date);//Deprecated
d.setTime(long time); //Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
System.out.println(d);
Ignore that answer, please and DynaFest read the API!
Similar Messages
-
Convert from String to Date for storing in SQL Server 2000
Hi,
I've accepted some values from a user using a form in HTML.Now using Servlets I transfer the value to my java code .
I want to know how can I convert a DATE accepted from the user thats presently in "String" format to the "datetime" format for SQL Server2000.
Please guide me with some steps and I shall be grateful.
ThanksThe java.text.SImpleDateFormat class is most probably of use.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String enteredDate = "25/12/2006";
java.util.Date utilDate = sdf.parse(enteredDate);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());You can then use the java.sql.Date with the "setDate()" method of a prepared statement. This method would be database independant, as you are setting an actual date, not depending on a specific format on the database end. -
Convert from String data type to Character data type
Hi...,
I'm a beginner. I try to make a program. But I don't know how to convert from string to data type. I try to make a calculator with GUI window. And when somebody put "+" to one of the window, I just want to convert it to Character instead of String.
Sorry of my bad english..
Please help me....
ThanksString s = "a+b";
char theplus = s.charAt(1); -
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); -
How can I convert from Modbus raw data to engineering units using a formula?
Within Lookout, I have several Modbus numerical input types that do not have a linear corespondence to the Engineering values they represent. How can I display these values accurately using a formula to convert from the raw data to an engineering value?
I don't quite understand your reply. I'm using Lookout 6.0.2, logged in as Administrator, in Edit Mode. The Modbus object is named RTU06_SAV. The Active member is 30002 with an alias of SAVfmSMT_RSL.
Following your instructions, I opened Object Explorer and right-clicked on RTU06_SAV.
This opened a menu containing: Refresh, Cut, Copy, Rename, Delete, Edit connections..., Edit Data Member Configuration, Configure Network Security and Properties.
I assumed that I should select Edit Data Member Configuration, but maybe I'm wrong.
Within Data Member Configuration I can set up Linear Scaling between Raw data and Engineering data. I know how to do that, but what I need to know is how to convert Raw data to Engineering data using a formula representing a non-linear transformation (such as a converion to a logarithmic value or perhaps a formula derived by fitting the formula to a curve on a calibration chart).
Once I have this my Engineering data can be represented on a control panel as both a numeric value AND as a correctly reading Gauge. It can also be properly represented on a HyperTrend graph.
What do you suggest? -
Convert from String to HashMap
Hi
Can any body pls tell us how to convert from String to HashMap
I have one string str="Col1=200, Col2=225";
So how can i convert that string varibale into HashMap?Hi
Can any body pls tell us how to convert from String
to HashMap
I have one string str="Col1=200, Col2=225";
So how can i convert that string varibale into
HashMap?
Map map = new HashMap();
String[] parts = str.split(", ");
for (int i = 0; i < parts.length; ++i) {
String[] entry = parts.split("=");
map.put(entry[0], entry[1]); -
Hi,
I have a question.
How do I convert from String to Integer?
Here is my code:
try{
String s="000111010101001101101010";
int q=Integer.parseInt(s);
answerStr = String.valueOf(q);
catch (NumberFormatException e)
answerStr="Error";
but, everytime when i run the code, i always get the ERROR.
is the value that i got, cannot be converted to int?
i've done the same thing in c, and its working fine.
thanks..6kyAngel wrote:
actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument. -
Convert from String to boolean ??
hi everyone..
is there any way to convert from String (as a class) to boolean (as a primitive type) ?
thunxI used : Boolean.valueOf(s).booleanValue(); ,I got the same error.What same error? Surely not this one:
cannot resolve simple in parseBoolean method??
equals is OK, but I think it is not convert method,
the prev. solutions by equals don't convert the value of s (String).Yes it does, for any reasonable definition of "converts". In fact, that is essentially how parseBoolean() is implemented. From the JDK 5.0 source code, class java.lang.Boolean:
return ((name != null) && name.equalsIgnoreCase("true")); -
Hello Frineds I want to convert from String to Long.
My String is like str="600 700 250 300" and I want to convert it to long and
get the total value in to the long variable.like the total of str in long varible should be 1850.
Thank You
Nilesh VasaniMaybe this would work?
StringTokenizer st = new StringTokenizer(yourString, " ");
long l = 0;
while(st.hasMoreTokens()) {
l += Long.parseLong(st.nextToken()).longValue();
} -
How do I convert from String to float?
Hi,
you can use a Double for example - assuming value is that string to parse
float f;
try { Double d = new Double(value); f = d.floatValue(); }
catch (NumberFormatException e) { f = 0.0; } // error - string value could not be parsed
// here use your float fHope, that helps
greetings Marsian
P.S.: the Double class is usefull for that, because you also can get intValue(), doubleValue() or longValue() out of it for example. The StreamTokenizer for example parses numbers also only to double. -
How to convert a String to Date format?
the user enter a date in string format and the date is save in the database.
The problem i am facing is i want to change from String to Date format.
Here is my codes:
public boolean insertData() throws Exception {
boolean validFlag = false;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = df.parse("05/18/05");
String MY_DATE_FORMAT = "yyyy-MM-dd";
String jobAdvertisementDate = new SimpleDateFormat(MY_DATE_FORMAT).format(d);
String sql = "INSERT INTO companyjob (CompanyID,JobID, JobAdvertisementDate ) " +
" VALUES ('" + companyID + "','" + jobID + "', '" + jobAdvertisementDate + "')";
System.out.println(sql);
validFlag = executeSQL(sql);
return validFlag;
}The date is save under jobAdvertisementDate.
My netbeans shows an error. There's a red line under DateFormat and parse inside my codes.
PLease help me. Reply asap!!BebeGirl wrote:
My netbeans shows an error. There's a red line under DateFormat and parse inside my codes.
Red Line? Sounds ominous. I wonder what it means.
So...what does the error say? -
How to convert a string to date and then compare it with todays date???
Hello.
I want to set a format first for my dates
DateFormate df = new SimpleDateFormate("yyyy-mm-dd");
once this is done then I want to convert any string to date object in the above formate
String str="2001-07-19";
Date d = null;
try{
d = df.parse(s);
}catch(ParseException pe) {
pe.printStackTrace();
First of all there is something wrong above,cus what I get for this is
Fri Jan 19 00:07:00 MST 2001
where as it should have been
2001-07-19... to my understanding.
once this part is done I need to get current date in the above set format and compare the
current date and the date I set.
I will appreciate the help.
Thanksfor the output part:
a date is a point in time
the output depends on the format you specify for output
using for example a SimpleDateFormat.
You only specified the format for parsing (which is independent for that of output) so java uses some default format ... see the DateFormat.format() method for details.
for the comparison stuff, I just posted a little code snippet in this forum a few minutes ago.
the hint is: Date.getTime() returns milliseconds after a fixed date
hth Spieler -
Date Formatting, Converting from String to Timestamp
I am trying to convert a string date to timestamp.
I have tried a couple of different ways to arrive at the end result.
I am basically trying to convert a date in the "dd-MM-yyyy" format to a timestamp.
If I use the following code, I get a date like this "18-May-2004 12:00:00 AM".
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy);
Date dContractDate = sdf.parse("18-05-2004");
long dateInMilli = dContractDate.getTime();
bHelp.bcontractdate = new Timestamp(dateInMilli);
How can I make this code display the current time not midnight or some defaulted value?
Thanks.I think a clever person would reuse their Date.classObject and call Date.setTime() as opposed to always
rolling out a new Date()
Not really a question of cleverness. Your code wins
nothing. Objects are not magically created and garbage collected in the ether.
The cost of creating a Date is nothing
compared to the cost of a format() call. True, but not valid a valid statement pertaining to the issue which is
"does always rolling dates suffer a performance hit?"
Plus you lost clarity Maybe you loose track of your code if you don't make new Objects all the time,
but I have never suffered from this.
Why do you think Sun provided the setDate() method?
and thread-safety.I have only had Thread issues when I didn't program them properly.
Luckilly I always program the correctly ;) (Touch wood)
The facts as I seem are thus:
Rolling new dates on a 1.83 GHZ PC incurrs on average
a 19% penalty. Here is the proof.
Save this program and save it as DateTest.java
If you don't want to waste the time here are the results of running it
through the default 10 iterations.
Running 10 iterations.
Reuse of dates is 27% more efficient
Reuse of dates is 17% more efficient
Reuse of dates is 18% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 17% more efficient
Reuse of dates is 17% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 20% more efficient
Reuse of dates is 18% more efficient
Gaining "nothing " actually = 19% on average
Low percent diff = 17 High percent diff = 27
Run it 100 times and it should still be around 19%
With the hi time being about 47% (Probably the result of garbage collecting)
//////////////////////////////////// <PROOF> ///////////////////////////////////////
import java.util.Date;
public class DateTest
DateTest()
public int run()
int percent = 0;
int loopCount = 0;
Date date = null;
int z=0;
long start1=0,end1=0,start2=0,end2=0,now=0;
int time1 = 0,time2 = 0;
now = System.currentTimeMillis();
date = new Date(now);
loopCount = 10000000;
start1 = System.currentTimeMillis();
for(z=0;z<loopCount;z++)
now = System.currentTimeMillis();
date.setTime(now);
end1 = System.currentTimeMillis();
start2 = System.currentTimeMillis();
for(z=0;z<loopCount;z++)
now = System.currentTimeMillis();
date = new Date(now); // use 'now' so test loops are =.
end2 = System.currentTimeMillis();
time1 = (int)(end1 - start1);
time2 = (int)(end2 - start2);
percent = ((time2-time1)*100/time2);
System.out.println("Reuse of dates is "+percent+"% more efficient");
return percent;
public static void main(String args[])
int z=0;
int lowP=100,hiP = 0; // lowpercent/highpercent
DateTest d = new DateTest();
int loopCount = 0;
long totals = 0;
int average = 0;
int values[];
int retVal = 0;
try // Yea olde Lazy person's command line handler :)
loopCount = Integer.parseInt(args[0]);
catch(Exception any)
loopCount = 10;
if(loopCount == 0)
loopCount = 10;
values = new int[loopCount];
System.out.println("Running "+loopCount+" iterations.");
for(z=0;z<loopCount;z++) //
retVal = d.run();
if(lowP > retVal)
lowP = retVal;
if(hiP < retVal)
hiP = retVal;
values[z] = retVal;
for(z=0;z<loopCount;z++)
totals += (long)values[z];
average = (int)(totals/loopCount);
System.out.println(" Gaining \"nothing \" actually = "+average+"% on average");
System.out.println("Low percent diff = "+lowP+" High percent diff = "+hiP);
}////////////////////////////////// </PROOF> /////////////////////////////////////////
Your "nothing" is in fact on average about a 19% performance hit. per call.
These inefficiencies build up and java is infested with the,
Was it not so the java would run much more efficiently than it now does.
Ask yourself; why did Sun supply the setDate() method???
(T) -
Problem in converting the String to Date with time zone GMT
Hi,
When I tried to convert the string 12/05/2009 to Date, the time zone is set to BST.On the other hand, for the date 12/12/2009, the time zone is set to GMT. What should I do to get the time zone as GMT all the time.?
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "12/05/2009";
System.out.println(myDate.toString());I think you are all missing the point. java.util.Date objects always alway always store the date as the number of milliseconds since 1/1/1970 UTC so the only TimeZone they have its the implicit UTC. When you use the Date.toString() method the toString() method gets the default time zone from your environment and formats the data accordingly. This means that the same Date object will, by default, produce a different result for France and Australia and the US.
So, if you have the date "12/5/2009" as a String then to convert it to a java.util.Date you must specify what TimeZone is implied. If it is your system time zone then you can just create a SimpleDateFormat object with the correct format and then use the parse() method to create the java.util.Date object and this will automatically be converted to UTC. If the date String represents some other time zone then you must explicitly set the time zone of the SimpleDateFormat object before parsing the string.
The same approach applies when converting a java.util.Date object to a String. If you want anything other than your system time zone then you must explicitly tell the SimpleDateFormat what time zone you want the result formatted for. -
I have a String in which i am storing the date which I have retrieved from database. How can I convert this String to a Date object and use Comparator for sorting.
String strCreatedDate1 = ((CVendorEmployees) vendoremployee1).getCreatedDate().toUpperCase();The date format which I will retrieve from String is mm/dd/yyyy.
I want to convert this into date and use it for sorting.
Thanx.Date dtTmp = new
SimpleDateFormat("dd-MM-yyyy").parse(((CVendorEmployee
s) vendoremployee1).getCreatedDate());
Calendar calendar = Calendar.getInstance();
calendar.setTime(dtTmp);
Now you have the date object do what ever you wish toBetter make thatnew SimpleDateFormat("MM/dd/yyyy")And no need for the Calendar stuff if all you want is a Date object.
Maybe you are looking for
-
Brand new A655 Satellite Laptop will connect to new Vizio lcd but not older Plasma tv via HDMI
Hey guys, So i just purchased a brand new Toshiba Satellite A665-S5183X and It works great with my new smaller bedroom LCD TV via HDMI and automatically connects when I plug in the HDMI. HOWEVER, my older HP 42" Plasma connected via HDMI will not rec
-
How to implement an abap program in a process chain
Hi, I have an ABAP Program which uploads data into a table. Now I want to implement this abap program in a process chain. Please could anyone tell me how this can be done. Thanks & Regards, Sushanth H.S.
-
hello Experts! Having Two systems DEV & PRD. DEV is created as Domain controller. while adding PRD in Domain getting following Message. RFC communications error with system/destination TMSADM@ DEV.DOMAIN_DEV Message no. XT101 Diagnosis An RFC error
-
Help! Problem with opening Mail
I've been having a hugely annoying problem with mail and preview, and I nor any of the wizards at my local mac store can't solve it to save their lives. So, I've come here, to the experts. First of all, neither program will open or provide any errors
-
Iphone Version 2 software update
Hi to you all i am been away on holiday for almost 3 weeks and not had access to the interner. Before i left i read on this website about an updated V2 software coming out at the end of june for the iphone. I have just conected mine and it says my ve