I have a simple problem while converting String to SQL date.
java.sql.Date sqlDate = getSqlDateFormat("2010-10-10");
Expected to store 2010-10-10 in the H2 database but it stores 2009-12-27 instead.
Any help will be appreciated.
public static java.sql.Date getSqlDateFormat(String dateInString) {
java.util.Date date = transformFromStringToDate(dateInString);
return convertUtilDateToSqlDate(date);
}
The method in turn calls transformFromStringToDate() to convert the input String into java.util.Date
public static java.util.Date transformFromStringToDate(String dateInString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd", Locale.ENGLISH);
java.util.Date utilDate = dateFormat.parse(dateInString);
return utilDate;
}
Finally I'm calling the convertUtilDateToSqlDate() to store it in the database
public static Date convertUtilDateToSqlDate(java.util.Date date)
{
Date sqlDate = new Date(date.getTime());
return sqlDate;
}
change your format to yyyy-MM-dd The year must be lowercase y rather than uppercase.
If you see the documentation of SimpleDateFormat Yis the Week year.
y is the field Year
Related
I tried to see questions about date convert issues between two database using java but didn't solve my problem.
Here is the current date to insert in my database with a DateTime format :
java.sql.Date SQLDateValue = new java.sql.Date(System.currentTimeMillis()) ;
preparedStatement.setDate(index, SQLDateValue);
And here is the Timestamp from an API named Vdoc, convert to String and i tried to convert it to java.sql.Date (DateTime) :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date DateValue = (java.util.Date) this.getWorkflowInstance().getValue(this.ListeChamps[i][2]);
String StringDateValue = DateValue.toString();
java.sql.Date SQLDateValue = new java.sql.Date (sdf.parse(StringDateValue).getTime());
preparedStatement.setDate(index, SQLDateValue);
The second line return a field value containing a String but i need to use toString().
The following error message is :
Failed to convert the date and / or time from a string.
Both of my date parameters are java.sql.date, i don't understand.
If you have an idea of what happens with this, it would be nice to help me.
Ezerah
Sorry for my bad english
Just construct the java.sql.Date from java.util.Date.
Call java.util.Date::getTime to extract the count of milliseconds from epoch. Pass that count to constructor of java.sql.Date.
In your case below should work.
java.util.Date DateValue = (java.util.Date) this.getWorkflowInstance().getValue(this.ListeChamps[i][2]);
java.sql.Date SQLDateValue = new java.sql.Date (DataValue.getTime());
preparedStatement.setDate(index, SQLDateValue);
try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date DateValue = **sdf.parse(**this.getWorkflowInstance().getValue(this.ListeChamps[i][2])**)**;
String StringDateValue = DateValue.toString();
java.sql.Date SQLDateValue = new java.sql.Date (sdf.parse(StringDateValue).getTime());
preparedStatement.setDate(index, SQLDateValue);
You can't cast String to Date, you should parse it
I have the below method in which date is coming as parameter that is in form of string and that parameter name is dateString as shown below and ultimately the date is converted and stored n form of java.sql.Date which is also return type of this method.
public static java.sql.Date getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
java.util.Date date = null;
java.sql.Date sqlDate = null;
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
date = df.parse(dateString);
sqlDate = new java.sql.Date(date.getTime());
} catch (Exception pe) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
return sqlDate;
}
Question:
I found that value is coming in this format 2014-07-23 (YYYY-MM-dd) and I want the return date (java.sql..Date) to be in 23-07-14 (dd-MM-YY).
This generates the date format you want - just use String as the return type instead of java.sql.Date:
public static String getSimpleDate11(String dateString) {
if (dateString == null) {
return null;
}
DateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dfOut = new SimpleDateFormat("dd-MM-yy");
try {
Date date = dfIn.parse(dateString);
return dfOut.format(date);
} catch (ParseException e) {
throw new RuntimeException(
"The date entered is invalid or has incorrect format"
+ dateString);
}
}
In case you need to convert the incoming "yyyy-MM-dd" String date to a java.sql.Date object you already did everything right in the code you posted in your question.
A java.sql.Date object, just like a java.util.Date, stores the date you give it internally in some format you, as a programmer, don't have to care about. You just have to know that the date is stored in the object and that you can get it out of the object whenever you need it. If you're interested in technical details you can google for it but, as I said, in your case this doesn't matter.
Whenever you need a java.util.Date object just use the one you get out of your original getSimpleDate11(...) function. Whenever you need a String representation of the date in a certain format, like "dd-MM-yy", take the java.util.Date and plug it into a DateFormat object initialized with the output format you want, just like I did in my first answer with DateFormat dfOut (the format(...) method of DateFormat can handle both, java.util.Date and java.sql.Date objects).
I'm trying to parse a string to get a Date object, but it's always returning Sun. December 30, 2012 for the date. Does anyone have any ideas on what I'm doing wrong?
I was using the same code using strings in YYYY-MM-dd format and it worked just fine, so I'm not sure why switching to this format is causing issues.
public static Date getDateObjFromStr(String dateStr)
{
DateFormat formatter = new SimpleDateFormat("MM/dd/YYYY");
Date dateObj;
try {
dateObj = formatter.parse(dateStr);
return dateObj;
} catch(Exception e) {
return null;
}
}
Case-sensitive
Uppercase Y represents week-based year.
Try using lowercase y instead
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Is it possible to do format a date of type String using a date formatter? I want to store my Date and Time in the Event class as Strings so that I don't need to convert the Strings loaded from a MYSQL database (using the types DATE and TIME) back into Date types so they can be stored in new Event objects. MySQL only accepts DATE in the format of YYYY-MM-DD and TIME in the format of HH:MM:SS but i want these to be formatted differently when i go to print them out in my program.
When i run this code i get an Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) error. If i try using parse() it won't compile because it only accepts Dates.
Main class
public Main() {
ArrayList<Event> events = new ArrayList<Event>();
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:MM:SS");
private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
//Stores current time and date
Date date;
Date time;
String d = "";
String t = "";
d= dateFormat.parse(date);
t= timeFormat.parse(time);
events.add(d, t);
//Print out newly formatted date and time when loaded from mysql
System.out.println(events.get(0).printDate());
System.out.println(events.get(0).printTime());
}
Events class
public class Event {
private String date;
private String time;
public Event(String d, String t) {
date = d;
time = t;
}
public String printDate() {
SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
public String printTime() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String newTime = format.format(time);
return newTime;
}
}
In Event, you should use Date type for date and time field.
This is a more appropriate representation for date and time value. And with them, you can use DateFormat to do whatever formatting you want
(It will be even better to use Joda time LocalDate and LocalTime for your date and time, but that's a bit off topic)
You can't format your dates because they are String objects and SimpleDateFormat needs Date objects.
You should consider a different way of storing them (either as Date or Calendar). See below:
public class Event
{
private Date date;
private Date time;
public Event(String d, String t)
{
String[] details = d.split("\\-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
date = c.getTime();
details = t.split(":");
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
time = c.getTime();
}
public String printDate()
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
// rest of you class can stay the way it is
}
You can format java.util.Date or java.sql.Date (which is subclass of java.util.Date) using date formatter, eg:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = df.format(date);
Using jdbc ResultSet getDate() method you can obtain java.sql.Date object which you can print in any format using method above
Similar techniques can also be used to parse string in any format into a java.util.Date object
Date date = df.parse(dateStr);
Check the javadoc for the right formatting codes. Try this:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
This is a method in an EJB for adding booking, I'm trying to set a to value of String Arr because Arr is a string which gets the form value in the Servlet and I want to do the same for d to value of String Dept. I'm using java.util.Date, it works for java.sql.Date but not for java.util.Date.
public void addBooking(String Arr, String Dept, String username, String roomnum){
BookingTableClass booking = new BookingTableClass();
Date a= Date.valueOf(Arr);//the problem is in these four lines
booking.setarrivalDate(a);
Date d= Date.valueOf(Dept);
booking.setdeptDate(d);
booking.setCustomerUsername(username);
Long rmnum = Long.valueOf(roomnum);
booking.setRoomNumber(rmnum);}
Maybe you're not using a correct format for the Date type and you have to specify the format that you're using, for this purpose use SimpleDateFormat class.
SimpleDateFormat textFormat = new SimpleDateFormat("yyyy-MM-dd");
String paramDateAsString = "2007-12-25";
Date myDate = null;
myDate = textFormat.parse(paramDateAsString);
Hope it helps. Best regards.
You can convert a java.util.Date into a java.sql.Date object like this:
java.util.Date now = new java.util.Date();
java.sql.Date date = new java.sql.Date(now.getTime());
That is, you obtain the java.util.Date equivalent in milliseconds and then use this value to initialize the java.sql.Date object.