Hello i am using struts2 but my textfield is getting Object from Java.util.date instead of its value
Javascript
start = moment(start).format();
alert(start);
2014-10-31T00:00:00+00:00
but when i try to use value of start in java object , it prints following object
java.util.GregorianCalendar[time=1416382200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Ulaanbaatar",offset=28800000,dstSavings=0,useDaylight=false,transitions=48,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=4,DAY_OF_MONTH=19,DAY_OF_YEAR=323,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=30,SECOND=0,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]
how can i get 2014-10-31T00:00:00+00:00 in java (struts2 ) object
Struts2 Getter and Setter
#Column(name="EVENT_START")
public Calendar getOrder_employee_start() {
return order_employee_start;
}
public void setOrder_employee_start(Calendar order_employee_start) {
order_employee_start.getTime();
this.order_employee_start = order_employee_start;
}
Are you using <s:date> tag to receive the date value on your jsp?
If not you should either return a String value which you could use directly in your textboxes.
SimpleDateFormat can be used to get the desired result.
For instance-
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Then call sdFormat.format(cal.getTime())
So, in your case you can do something like sdFormat.format(order_employee_start.getTime())
Related
I know I'm probably doing something wrong, but I am trying to format a Date that is currently stored inside of a string but it won't let me parse it to a String because it doesn't recognize it as a Date (because it's in a String variable) and won't let me format it because it cannot format it in its current state. For reference, I am making a time clock application.
I apologize if I'm doing something stupid but I am fairly new to this and have never used SimpleDateFormat before. I put some snippets of code below:
ArrayList<String> punchHistoryTimes = new ArrayList<String>();
SimpleDateFormat sdf =new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public void updatePunchHistory(Sheet sheet){
for(int rowNum:rowNumbers){
punchHistoryTimes.add(sheet.getRow(rowNum).getCell(1).getStringCellValue());
punchHistory.add(new JLabel(sheet.getRow(rowNum).getCell(0).getRichStringCellValue().getString()+ " " + sheet.getRow(rowNum).getCell(1).getRichStringCellValue().getString()+ " " + sheet.getRow(rowNum).getCell(2).getRichStringCellValue().getString()));
}
}
//other code is above this but not relevant to the issue
currentEmployee.setEndTime(sdf.format(currentDate));
if(punchHistory.get(punchHistory.size()-1).getText().contains("Clocked In")){
calcTimeWorked(punchHistory.get(punchHistoryTimes.size()-1).getText(),currentEmployee.getEndTime());
}else{
//This line below is where the error is happening
//value of currentEmployee.getStartTime() at error: 1654653731536
//value of currentEmployee.getEndTime() at error: 07-06-2022 21:02:12
//Both currentEmployee.getStartTime() and currentEmployee.getEndTime() are stored as Strings
calcTimeWorked(currentEmployee.getStartTime(),currentEmployee.getEndTime());
}
currentEmployee.setHoursWorked(differenceInTime);
I tried using the debugger and it shows the error is that it cannot parse 1654653731536. I understand the issue but cannot get a solution. I believe the issue is because when it stores the value in the excel file it is storing the date as a string but then when it pulls the date back out of the excel later (the application would have been closed between these events) it views it as a string and does not recognize that there is a Date inside of the String. Is there any way to cast the String 1654653731536 to a Date?
I'm doing an integration testing with DBUnit (2.49) + Hibernate (4.1.3) following this tutorial.
Production database : Oracle 10
Test database : Hsqldb 2.3.3
Context
My data contains the current format of date : yyyy/MM/dd. However,according to DBUnit faq, DBUnit only supports this format yyyy-mm-dd hh:mm:ss.fffffffff, so I had to create a new format for TimeStamp.
How I tried to fix it
I created a CustomTimeStampDataType based on this tutorial. I changed this part:
String formats[] = {"yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm a", "yyyy-MM-dd HH:mm:ss.fffffffff"};
into this one:
String formats[] = {"yyyy/MM/dd"};
I created a CustomeDataTypeFactory following the same tutorial. I only make it extend Oracle10DataTypeFactory rather than DefaultDatatTypeFactory.
In HibernateDBUnitTestCase, I override setDatabaseConfig() with the following:
#Override
protected void setUpDatabaseConfig(DatabaseConfig config){
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new CustomDataTypeFactory());
}
But I got new errors
I ran a unit test and got this error.
org.dbunit.dataset.datatype.TypeCastException: Unable to typecast value <1997/02/14> of type <java.lang.String> to TIMESTAMP
at org.dbunit.dataset.datatype.TimestampDataType.typeCast(TimestampDataType.java:120)
at org.dbunit.dataset.datatype.TimestampDataType.setSqlValue(TimestampDataType.java:176)
at org.dbunit.database.statement.SimplePreparedStatement.addValue(SimplePreparedStatement.java:73)
at org.dbunit.operation.RefreshOperation$RowOperation.execute(RefreshOperation.java:189)
at org.dbunit.operation.RefreshOperation.execute(RefreshOperation.java:113)
at org.dbunit.AbstractDatabaseTester.executeOperation(AbstractDatabaseTester.java:190)
at org.dbunit.AbstractDatabaseTester.onSetup(AbstractDatabaseTester.java:103)
at org.dbunit.DatabaseTestCase.setUp(DatabaseTestCase.java:156)
at test.HibernateDbUnitTestCase.setUp(HibernateDbUnitTestCase.java:85)
at test.PlayerTest.setUp(PlayerTest.java:117)
Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
at java.sql.Timestamp.valueOf(Unknown Source)
at org.dbunit.dataset.datatype.TimestampDataType.typeCast(TimestampDataType.java:116)
... 20 more
That was weird, it seemed like my CustomTimeStamp was not called, so I changed the date in the dataset using the default format : 1997-02-14 00:00:00.0, and ran the unit test again. Then I got:
org.dbunit.dataset.datatype.TypeCastException: Unable to typecast value <1997-02-14 00:00:00.0> of type <java.lang.String> to TIMESTAMP
at test.CustomTimestampDataType.typeCast(CustomTimestampDataType.java:69)
at test.CustomTimestampDataType.setSqlValue(CustomTimestampDataType.java:84)
at org.dbunit.database.statement.SimplePreparedStatement.addValue(SimplePreparedStatement.java:73)
at org.dbunit.operation.RefreshOperation$RowOperation.execute(RefreshOperation.java:189)
at org.dbunit.operation.RefreshOperation.execute(RefreshOperation.java:113)
at org.dbunit.AbstractDatabaseTester.executeOperation(AbstractDatabaseTester.java:190)
at org.dbunit.AbstractDatabaseTester.onSetup(AbstractDatabaseTester.java:103)
at org.dbunit.DatabaseTestCase.setUp(DatabaseTestCase.java:156)
at test.HibernateDbUnitTestCase.setUp(HibernateDbUnitTestCase.java:85)
at test.PlayerTest.setUp(PlayerTest.java:117)
That means CustomTimeStamp was actually called. Seems like, the problem stemed from DatabaseTestCase.setUp which somehow called the wrong TimeStampDataType.
How could I fix this issue?
My first option was to replace every yyyy/MM/dd into yyyy-mm-dd in the dataset using regular expressions. This worked fine, until I had to test a method that selected a date based on a request (so the format is yyyy-mm-dd) and compared it to the current date. ( so the format is yyyy / mm / dd). Hsqldb can't compare two dates with different format.
My second option was to decompile dbunit.jar, rewrite TimeStampDataType based on the tutorial. I'm unfamiliar with bytecode writing so before entering uncharted waters, I wanted to know if you had another solution.
Thank you in advance
Fixed it!
So I ended up using my second option.
This is the detailed path for those who need it.
Download dbUnit.2.2.source.jar
Unzip the jar
Go to Eclipse, File > New > Java Project
Uncheck "Use default location"
In Location : specify the path to the new folder created from the jar
Click on Finish
Modify the TimestampDataType.java (if needed)
Instead of ts = java.sql.Timestamp.valueOf(stringValue); use the code below
String formats[] =
{"dd/MM/yyyy HH:mm:ss.SS"}; //and more depending on your need
Timestamp ts = null;
for (int i = 0; i < formats.length; i++)
{
SimpleDateFormat sdf = new SimpleDateFormat(formats[i]);
try {
java.util.Date date = sdf.parse(stringValue);
ts = new Timestamp(date.getTime());
return ts;
}
catch( ParseException e) {
}
Modify the DateDataType.java (if needed)
Instead of return java.sql.Date.valueOf(stringValue); , use the code below
String formats[] =
{"dd/MM/yyyy"}; //and more depending on your need
for (int i = 0; i < formats.length; i++)
{
SimpleDateFormat sdf = new SimpleDateFormat(formats[i]);
try {
java.util.Date date = sdf.parse(stringValue);
java.sql.Date datesql = new java.sql.Date(date.getTime());
return datesql;
}
catch( ParseException e) {
}
}
Right-click on your project, then Export
Select JAR file, then Next
Fill the export destination then Finish.
You just have to add this new jar to the library to make it work.
How do you add days to a date in SmartGwt. I found this question and found that I can use CalendarUtil.addDaysToDate(dateToAddTo, daysToAddToDateAsInteger)); but addDaysToDate() is static void. What is the point of a method that can "add days to a date" if it does not return anything?
How do I use this method? I want to do something like this.
Date newDate = dateToAddTo + daysToAddToDate;
Here is a simplified version of my code.
if (listGridRecord.getAttribute("expirationDays") != null) {
CalendarUtil.addDaysToDate((Date) endDate.getValue(), Integer.parseInt(listGridRecord.getAttribute("expirationDays")));
listGridRecord.setAttribute("expirationDate", (Date) endDate.getValue());
} else {
listGridRecord.setAttributeAsJavaObject("expirationDate", null);
}
Here is a link to the javadocs
This method changes the object that is passed as parameter.
Date date = new Date();
long checkBeforeChange = date.getTime();
CalendarUtil.addDaysToDate(date, 1);
long checkAfterChange = date.getTime();
if(checkBeforeChange != checkAfterChange)
Window.alert("It works ;)");
Your code should be something like that:
if (listGridRecord.getAttribute("expirationDays") != null) {
Date tmpDate = endDate.getValue();
CalendarUtil.addDaysToDate(tmpDate, Integer.parseInt(listGridRecord.getAttribute("expirationDays")));
listGridRecord.setAttribute("expirationDate", tmpDate);
} else {
listGridRecord.setAttributeAsJavaObject("expirationDate", null);
}
When doing (Date) endDate.getValue() you get a copy of Date object thus you don't see any change.
I figured out what I was doing wrong with the help of #Adam. I created a new Date variable called expireationDate and set it to (Date) endDate.getValue(); after this I used it to do the calculation.
if (listGridRecord.getAttribute("expirationDays") != null) {
Date expirationDate = (Date) endDate.getValue();
CalendarUtil.addDaysToDate(expirationDate, Integer.parseInt(listGridRecord.getAttribute("expirationDays")));
listGridRecord.setAttribute("expirationDate", expirationDate);
} else {
listGridRecord.setAttributeAsJavaObject("expirationDate", null);
}
First of all, you can wrap all those utility methods you need in your own utility class (private constructor), where e.g. MyDateUtilsClassName.addDays(Date, int) will return new instance, leave parameter unmodified.
When it comes to Date manipulation, in Gwt you can use standard java.util.Date methods, even those deprecated ones like setMinutes, setHours etc. Even when you see com.google.gwt.user.datepicker.client.CalendarUtil method, they are used there.
If it's not server side, but client side, you should not care much about #Deprecated on those methods. Gwt compiles them to javascript anyway. You should be aware of java.util.Calendar. As far as I remember, it is not supported at all.
The problem I am having is with the PrimesFaces 3.4.1 calendar. When using the popup date picker activated either through the button or on input field focus you can only select valid dates which work fine, happy days!
The issues comes when you manually add a date into the input field, if you add an invalid date the PrimeFaces calendar component takes its best guess at converting this into a valid date and then sending it, meaning that back-end validation is a no go. Some interesting translations below:
30/02/2012 becomes 2/6/2014
322/05/2012 becomes 5/10/2038
01/14/2012 becomes 4/1/2012
To recreate this madness have a look at the PrimeFaces Calendar Showcase.
I have seen solution around using the readOnlyInput='true' attribute but that only seems to prevent letters being entered in the field not number or slashes. Below is one instance of the calendar I have implemented:
<p:calendar id="fldDateOfBirth"
value="#{pc_CreateUser.user.dateOfBirth}"
binding="#{pc_CreateUser.dobComp}"
navigator="true"
pattern="dd/MM/yyyy"
maxlength="10"
yearRange="-100"
validator="#{pc_CreateUser.validateDOB}"
title="#{msg.user_date_format_default_tip}"
converterMessage="#{msg.user_error_dob_invalid}"
readOnlyInput="true"
showOn="button" />
Solution wise I am open to any suggestions:
Is this a common issues in PrimeFaces? Is there a trick I can use to
fix it?
Could I use JavaScript to validate the date before it's sent or to
block all user input entirely?
Anything else I haven't thought of!
Thanks in advance, this has been causing me issues for weeks!
The <p:calendar> uses under the covers SimpleDateFormat which in turn uses by default lenient parsing, causing the overflowed values to roll over into the next date metric level. E.g. 32 January would become 1 February, etc.
In plain Java terms, this can be turned off by DateFormat#setLenient(), passing false. See also among others this question: validating a date using dateformat.
In JSF terms, you basically need to provide a custom converter which uses a non-lenient DateFormat. Fortunately, standard JSF already provides such one out the box in flavor of <f:convertDateTime>, so you could just make use of it directly.
<p:calendar ...>
<f:convertDateTime pattern="dd/MM/yyyy" />
</p:calendar>
In faces-config.xml add this
<converter>
<converter-id>localDateConverter</converter-id>
<converter-class>com.utility.LocalDateConverter</converter-class>
</converter>
In the above class i.e LocaldateConverter add this below code
/**
* #param facesContext .
* #param uiComponent .
* #param input .
* #return Object .
*/
#Override
public Object getAsObject(final FacesContext facesContext, final UIComponent uiComponent, final String input) {
if (StringUtils.isBlank(input)) {
return null;
}
final String componentPattern = (String) uiComponent.getAttributes().get("datePattern");
final String patternToUse = componentPattern != null ? componentPattern : CommonConstants.OUTPUT_DATE_FORMAT;
try {
final DateFormat fmt = new SimpleDateFormat(patternToUse);
Date convertedDate = new java.sql.Date(fmt.parse(input).getTime());
return convertedDate;
} catch (Exception e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Date Format", null));
}
}
/**
* #param facesContext .
* #param uiComponent .
* #param obj .
* #return String .
*/
#Override
public String getAsString(final FacesContext facesContext, final UIComponent uiComponent, final Object obj) {
if (obj==null) {
return null;
}
final Date date = (Date) obj;
return date.toString();
}
I am taking date of birth as input using JSON
{"dateOfBirth":"1973-08-26"}
This field exists in Person.java class
import java.util.Date;
public class Person {
Date dateOfBirth;
//Some other fields
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
}
This is mapped to person table in mysql database.
I am querying the database like:
entityId = (Long) session.selectOne("ValidatePerson", registerUserRequestParams);
Following are the entries I am making in my mapper.xml
<select id="ValidatePerson" parameterMap="ValidatePersonMap" resultType="long">
select person.entityId
from person
where
//Some other Validation checks
<if test="dateOfBirth != null">
and person.dateOfBirth = #{dateOfBirth}
</if>
);
</select>
I have a prameter Map as
<parameterMap id="ValidatePersonMap" type="java.util.HashMap">
<parameter property="dateOfBirth" javaType="java.util.Date" jdbcType="DATE" mode="IN"/>
</parameterMap>
I am not able to get any result from database.It does not select any row even though value exists.I have checked that none of other validation checks are failing. If I pass dateOfBirth as null in JSON then then I get result.
I have also written a test case and setting request as follows:
Date dob = new Date(73,7,26);
request.setDateOfBirth(dob);
When I pass values from test case as mentioned above I get result from database.
Problem occurs only when i get request parameters using json.
The format of JSOn and the format stored in DB are same
One work around I have is to manually convert java.util.Date to String in above format and pass it as string. But this is pretty bad approach and client would not like it.
Use Timestamp. Consider Joda time plug. ...and read this answer.
These three will absolutely do the magic.
Good luck!
Have you tried formatting the java date. Maybe the formats are different so it can't match between the JSON and the one stored in your db?
This worked for me:
mysql attribute type is Timestamp
and I format the date for JSON in Java like this:
Date d = new Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
String sd = sdf.format(d);
java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("HH:MM:ss");
String fakeit =sd+"T"+sdf2.format(d);
I then use fakeit