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.
Related
Here's my code:
public static String getStringFormat(Date inputDate, String timeZone){
String strFormat = null;
try{
final TimeZone computedTimeZone = TimeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(timeZone));
DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.ISO_8601);
strFormat = dateTimeFormat.format(inputDate, computedTimeZone);
Date d = new Date(strFormat);
strFormat = dateTimeFormat.format(d, TimeZone.createTimeZone(0));
String[] s = strFormat.split("\\+");
strFormat = s[0];
}catch(Exception e){
Console.log(e.getMessage());
}
return strFormat;
}
For input, new Date() and Etc/GMT+3 this function returns null. What could be wrong?
Error
Error: NullPointerException: undefined
at NBF_g$.QBF_g$ [as createError_0_g$] (NullPointerException.java:40)
at NBF_g$.ub_g$ [as initializeBackingError_0_g$] (Throwable.java:113)
at NBF_g$.bb_g$ (Throwable.java:61)
at NBF_g$.Ib_g$ (Exception.java:25)
at NBF_g$.avq_g$ (RuntimeException.java:25)
at NBF_g$.gfs_g$ (JsException.java:34)
at new NBF_g$ (NullPointerException.java:27)
at new wou_g$ (JSONString.java:43)
The method TimeZoneInfo.buildTimeZoneData(String tzJSON) doesn't accept the name of the zone, but needs a JSON string full of the details of how that zone works. It turns out that the browser doesn't come to you with all of the details of how all time zones work, so your app has to already be prepared to handle them.
GWT ships with all of the timezones (though they are currently a little out of date, and should be updated in this next release), but you have to tell the compiler which ones you want, or it will compile them out. The full list of all possible timezones and their offsets, etc is not small, so I would encourage you to limit the list.
These are stored in the constants interface TimeZoneConstants. Here is how you might use it:
TimeZoneConstants constants = GWT.create(TimeZoneConstants.class);
// This is the shorthand for TimeZone.createTimeZone(TimeZoneInfo.buildTimeZoneData(...))
TimeZone computedTimeZone = TimeZone.createTimeZone(constants.americaAdak());
//...
If you want to use the timezone string instead, say, passed from the server, you could build a map of the possible timezones that are supported. Be aware though that the full map is very large (200KB just for the timezones in the "America/..." group).
computedTimeZone = TimeZone.createTimeZone(constants.americaAdak());
zones.put(computedTimeZone.getID(), computedTimeZone);
computedTimeZone = TimeZone.createTimeZone(constants.americaAnchorage());
zones.put(computedTimeZone.getID(), computedTimeZone);
computedTimeZone = TimeZone.createTimeZone(constants.americaAnguilla());
zones.put(computedTimeZone.getID(), computedTimeZone);
//...
Then you can read out a specific item from the map as needed:
String tzName = Window.prompt("Enter a timezone name", "America/Chicago");
DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.ISO_8601);
String strFormat = dateTimeFormat.format(inputDate, zones.get(tzName));
//...
In your comment, you clarified the question, that you only need to deal with offsets, not the full TimeZone string format, i.e. Etc/GMT+3, meaning "Offset of +3 hours from GMT". This is easier to handle - simply parse out the +3 into a number, and use the TimeZone.createTimeZone(int timeZoneOffsetInMinutes) method. This will not understand daylight savings time, but that wouldn't be possible without the full name of the timezone or list of offsets, etc (which gets to why that JSON is so large).
//TODO, implement parse(), don't forget about negative numbers
int offsetInHours = parse(timeZone);
TimeZone computedTimeZone = TimeZone.createTimeZone(60 * offsetInHours);
//...
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.
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())
These are the basic conditions set in my code.
t1 = new JFormattedTextField(new SimpleDateFormat("dd-MM-yyyy"));
t1.setValue(new java.util.Date());
java.util.Date searchDate=(java.util.Date)t1.getValue();
Retrieving Date from the Result Set.
Date Date1 = rs.getDate("Date1");
I wanted to know whether this condition for matching the dates i enter and for retrieving the dates from database is correct or not. I am new in the world of coding.
if(new java.sql.Date(searchDate.getTime()).equals(Date1))
{
... //code
}
Nevermind...
making it...
java.sql.Date sqlSearchdate = new java.sql.Date(searchDate.getTime());
and
if(sqlSearchdate.equals(Date1)
{
...
}
solved the problem. This was so silly. My bad for asking such a question.
Yes that should work, according to http://www.mkyong.com/java/how-to-compare-dates-in-java/ though i'm not sure why you're creating a new Date object in the if statement.
My java class (servlet) has been running fine, but recently, I noticed a problem.
In my database, I have a Date column called 'Full_Expiration_Date'. If one was entered it will store it like '2010-11-17'. If one wasn't entered, is stores it like '0000-00-00'.
In my class, I call the records from the db, and look at the 'Full_Expiration_Date' field to see if it has a date or not. If it does, I execute a few lines of code that check to see if before today's date, and if the date is NOT today's date - if both those conditions are met, the coupon has expired.
So my code works just fine when there IS an expiration date specified, but fails when '0000-00-00' is in the field.
I'm generating an array of information for each coupon in the db table. Once the checking is complete and the array is filled, its sent as a request attribute.
Here's a snippet of my code for this process -
rs = stmt.executeQuery("select Full_Expiration_Date from coupons");
//will hold value from "Full_Expiration_Date" field in db
java.sql.Date expirationDate = null;
//today's date - used for comparison
java.util.Date today = new java.util.Date();
while(rs.next()) {
//get expiration date from db for this record
expirationDate = rs.getDate(12);
if(expirationDate == null) { //should be if the field is 0000-00-00, right?
//don't do any checking against
//expiration date, this record
//doesn't have one
couponList[counter][11] = "";
} else { //10
if(expirationDate.before(today) & !today.equals(expirationDate)) {
couponList[counter][11] = "expired";
} else { //11
couponList[counter][11] = "";
}//if
}//if
counter++;
}//while
Can someone pinpoint what I'm doing wrong here? I'm certain, after testing, that it has to do with the field being 0000-00-00.
0000-00-00 is an invalid date that can't be parsed by Java. You need to allow nulls in that field so that MySQL will stop inserting 0s and that way your if(expirationDate == null) check will actually work.
This is stupid behavior IMO and you should "fix it" by turning on Strict mode. http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_no_zero_date
You can work around this using MySQL's "zeroDateTimeBehavior" configuration property. In your connection properties set:
"zeroDateTimeBehavior" to "convertToNull"
Anytime a 0000-00-00 date is retrieved, it will return null instead of throwing an exception.
Reference: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html