Java Examples for java.sql.Timestamp

The following java examples will help you to understand the usage of java.sql.Timestamp. These source code samples are taken from different open source projects.

Example 1
Project: dbfit-master  File: SqlTimestampParseDelegate.java View source code
public static Object parse(String s) throws Exception {
    try {
        return java.sql.Timestamp.valueOf(s);
    } catch (IllegalArgumentException iex) {
        try {
            return new java.sql.Timestamp(java.sql.Date.valueOf(s).getTime());
        } catch (IllegalArgumentException iex2) {
            try {
                java.util.Date ud = dtf.parse(s);
                return new java.sql.Timestamp(ud.getTime());
            } catch (ParseException pex) {
                java.util.Date ud = df.parse(s);
                return new java.sql.Timestamp(ud.getTime());
            }
        }
    }
}
Example 2
Project: dbfit-teradata-master  File: SqlTimestampParseDelegate.java View source code
public static Object parse(String s) throws Exception {
    try {
        return java.sql.Timestamp.valueOf(s);
    } catch (IllegalArgumentException iex) {
        try {
            return new java.sql.Timestamp(java.sql.Date.valueOf(s).getTime());
        } catch (IllegalArgumentException iex2) {
            try {
                java.util.Date ud = dtf.parse(s);
                return new java.sql.Timestamp(ud.getTime());
            } catch (ParseException pex) {
                java.util.Date ud = df.parse(s);
                return new java.sql.Timestamp(ud.getTime());
            }
        }
    }
}
Example 3
Project: fastjson-master  File: TypeUtilsTest.java View source code
public void test_cast_to_Timestamp_calendar() throws Exception {
    long millis = System.currentTimeMillis();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(millis);
    JSONObject json = new JSONObject();
    json.put("date", calendar);
    Assert.assertEquals(new java.sql.Timestamp(millis), json.getObject("date", java.sql.Timestamp.class));
}
Example 4
Project: jackson-databind-master  File: TestTimestampDeserialization.java View source code
// As for TestDateDeserialization except we don't need to test date conversion routines, so
// just check we pick up timestamp class
public void testTimestampUtil() throws Exception {
    long now = 123456789L;
    java.sql.Timestamp value = new java.sql.Timestamp(now);
    // First from long
    assertEquals(value, new ObjectMapper().readValue("" + now, java.sql.Timestamp.class));
    String dateStr = serializeTimestampAsString(value);
    java.sql.Timestamp result = new ObjectMapper().readValue("\"" + dateStr + "\"", java.sql.Timestamp.class);
    assertEquals("Date: expect " + value + " (" + value.getTime() + "), got " + result + " (" + result.getTime() + ")", value.getTime(), result.getTime());
}
Example 5
Project: ormlite-core-master  File: TimeStampTypeTest.java View source code
@Test
public void testTimeStamp() throws Exception {
    Class<LocalTimeStamp> clazz = LocalTimeStamp.class;
    Dao<LocalTimeStamp, Object> dao = createDao(clazz, true);
    GregorianCalendar c = new GregorianCalendar();
    c.set(GregorianCalendar.MILLISECOND, 0);
    long millis = c.getTimeInMillis();
    java.sql.Timestamp val = new java.sql.Timestamp(millis);
    String format = "yyyy-MM-dd HH:mm:ss.SSSSSS";
    DateFormat dateFormat = new SimpleDateFormat(format);
    String valStr = dateFormat.format(val);
    LocalTimeStamp foo = new LocalTimeStamp();
    foo.timestamp = val;
    assertEquals(1, dao.create(foo));
    testType(dao, foo, clazz, val, val, val, valStr, dataType, TIME_STAMP_COLUMN, false, true, true, false, true, false, true, false);
}
Example 6
Project: isis-master  File: DateConverterForJavaSqlTimestamp.java View source code
private java.sql.Timestamp convert(String valueStr) {
    try {
        Date parsed = newSimpleDateFormatUsingDateTimePattern().parse(valueStr);
        return new java.sql.Timestamp(parsed.getTime());
    } catch (ParseException ex) {
        try {
            return new java.sql.Timestamp(newSimpleDateFormatUsingDatePattern().parse(valueStr).getTime());
        } catch (ParseException ex2) {
            throw new ConversionException("Value cannot be converted as a date/time", ex);
        }
    }
}
Example 7
Project: eclipselink.runtime-master  File: MutableAttributeObject.java View source code
public static MutableAttributeObject example1() {
    MutableAttributeObject container = new MutableAttributeObject();
    long timeNow = System.currentTimeMillis();
    // byte[] with all values set to 1
    byte[] someBytes = new byte[128];
    java.util.Arrays.fill(someBytes, (byte) 1);
    container.setByteArray(someBytes);
    // java.util types
    container.setUtilDate(new java.util.Date(timeNow));
    java.util.Calendar cal = java.util.Calendar.getInstance();
    cal.setTimeInMillis(timeNow);
    container.setUtilCalendar(cal);
    // java.sql types
    container.setSqlTime(new java.sql.Time(timeNow));
    container.setSqlDate(new java.sql.Date(timeNow));
    container.setSqlTimestamp(new java.sql.Timestamp(timeNow));
    // custom date subclass
    container.setDateSubclass(new DateSubclass());
    return container;
}
Example 8
Project: white-elephant-master  File: TimeZoneConversion.java View source code
public static java.sql.Timestamp roundTimestampToDay(java.sql.Timestamp timestamp, String timezoneId) {
    TimeZone timezone = TimeZone.getTimeZone(timezoneId);
    Calendar cal = Calendar.getInstance(timezone);
    cal.setTimeInMillis(timestamp.getTime());
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return new java.sql.Timestamp(cal.getTimeInMillis());
}
Example 9
Project: mfh-app-framework-master  File: TimestampDeserializer.java View source code
@SuppressWarnings("unchecked")
protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {
    if (val == null) {
        return null;
    }
    if (val instanceof java.util.Date) {
        return (T) new java.sql.Timestamp(((Date) val).getTime());
    }
    if (val instanceof Number) {
        return (T) new java.sql.Timestamp(((Number) val).longValue());
    }
    if (val instanceof String) {
        String strVal = (String) val;
        if (strVal.length() == 0) {
            return null;
        }
        DateFormat dateFormat = parser.getDateFormat();
        try {
            Date date = (Date) dateFormat.parse(strVal);
            return (T) new Timestamp(date.getTime());
        } catch (ParseException e) {
        }
        long longVal = Long.parseLong(strVal);
        return (T) new java.sql.Timestamp(longVal);
    }
    throw new JSONException("parse error");
}
Example 10
Project: oddjob-master  File: SQLConversionsTest.java View source code
public void testDateConversions() throws ArooaParseException, NoConversionAvailableException, ConversionFailedException, ParseException {
    ArooaSession session = new OddjobSessionFactory().createSession();
    ArooaConverter converter = session.getTools().getArooaConverter();
    DateType date = new DateType();
    date.setDate("2009-12-25");
    date.setFormat("yyyy-MM-dd");
    long expected = date.toDate().getTime();
    java.sql.Date sqlDate = converter.convert(date, java.sql.Date.class);
    java.sql.Time time = converter.convert(date, java.sql.Time.class);
    java.sql.Timestamp timestamp = converter.convert(date, java.sql.Timestamp.class);
    assertEquals(expected, sqlDate.getTime());
    assertEquals(expected, time.getTime());
    assertEquals(expected, timestamp.getTime());
}
Example 11
Project: seasar2-master  File: SqlTimestampConverter.java View source code
public Object convert(final Object source, final Class destClass, final ConversionContext context) {
    if (source == null) {
        return null;
    }
    if (shallowCopy && source instanceof java.sql.Timestamp) {
        return source;
    }
    if (source instanceof Date) {
        return toTimestamp((Date) source);
    }
    if (source instanceof Calendar) {
        return toTimestamp((Calendar) source);
    }
    if (source instanceof Number) {
        return toTimestamp((Number) source);
    }
    if (source instanceof String) {
        final DateFormat dateFormat = context.getTimestampFormat();
        if (dateFormat != null) {
            return toTimestamp((String) source, dateFormat);
        }
    }
    return null;
}
Example 12
Project: typhon-master  File: TimestampDeserializer.java View source code
@SuppressWarnings("unchecked")
protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {
    if (val == null) {
        return null;
    }
    if (val instanceof java.util.Date) {
        return (T) new java.sql.Timestamp(((Date) val).getTime());
    }
    if (val instanceof Number) {
        return (T) new java.sql.Timestamp(((Number) val).longValue());
    }
    if (val instanceof String) {
        String strVal = (String) val;
        if (strVal.length() == 0) {
            return null;
        }
        DateFormat dateFormat = parser.getDateFormat();
        try {
            Date date = (Date) dateFormat.parse(strVal);
            return (T) new Timestamp(date.getTime());
        } catch (ParseException e) {
        }
        long longVal = Long.parseLong(strVal);
        return (T) new java.sql.Timestamp(longVal);
    }
    throw new JSONException("parse error");
}
Example 13
Project: WCFrameWork-master  File: TimestampDeserializer.java View source code
@SuppressWarnings("unchecked")
protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {
    if (val == null) {
        return null;
    }
    if (val instanceof java.util.Date) {
        return (T) new java.sql.Timestamp(((Date) val).getTime());
    }
    if (val instanceof Number) {
        return (T) new java.sql.Timestamp(((Number) val).longValue());
    }
    if (val instanceof String) {
        String strVal = (String) val;
        if (strVal.length() == 0) {
            return null;
        }
        DateFormat dateFormat = parser.getDateFormat();
        try {
            Date date = (Date) dateFormat.parse(strVal);
            return (T) new Timestamp(date.getTime());
        } catch (ParseException e) {
        }
        long longVal = Long.parseLong(strVal);
        return (T) new java.sql.Timestamp(longVal);
    }
    throw new JSONException("parse error");
}
Example 14
Project: Consent2Share-master  File: CheckTime.java View source code
public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    Timestamp currentTimestamp = new java.sql.Timestamp(calendar.getTime().getTime());
    System.out.println(currentTimestamp);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
    //2014-08-11T09:36:34.388Z
    System.out.println(sdf.format(new Date()));
}
Example 15
Project: CrossFitr-master  File: DateToTimestamp.java View source code
public static void main(String[] args) {
    try {
        String str_date = "11-June-07";
        DateFormat formatter;
        Date date;
        formatter = new SimpleDateFormat("dd-MMM-yy");
        date = formatter.parse(str_date);
        java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
        System.out.println("Today is " + timeStampDate);
    } catch (ParseException e) {
        System.out.println("Exception :" + e);
    }
}
Example 16
Project: kfs-master  File: PaymentRequestDocumentFixture.java View source code
@Override
public PaymentRequestDocument newRecord() {
    PaymentRequestDocument obj = new PaymentRequestDocument();
    java.sql.Timestamp timeStamp = new java.sql.Timestamp(SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime());
    java.sql.Date date = new java.sql.Date(SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime());
    obj.setPurapDocumentIdentifier(311);
    obj.setDocumentNumber("31");
    //            obj.setApplicationDocumentStatus(PaymentRequestStatuses.APPDOC_DEPARTMENT_APPROVED);
    obj.setPurchaseOrderIdentifier(21);
    obj.setPostingYear(2009);
    obj.setInvoiceDate(date);
    obj.setInvoiceNumber("1001");
    obj.setVendorInvoiceAmount(new KualiDecimal(19000));
    obj.setVendorPaymentTermsCode("00N30");
    obj.setVendorShippingPaymentTermsCode("AL");
    obj.setPaymentRequestPayDate(date);
    obj.setPaymentRequestCostSourceCode("EST");
    obj.setPaymentRequestedCancelIndicator(false);
    obj.setPaymentAttachmentIndicator(false);
    obj.setImmediatePaymentIndicator(false);
    obj.setHoldIndicator(false);
    obj.setPaymentRequestElectronicInvoiceIndicator(false);
    obj.setVendorHeaderGeneratedIdentifier(2013);
    obj.setVendorDetailAssignedIdentifier(0);
    obj.setVendorName("BESCO WATER TREATMENT INC");
    obj.setVendorLine1Address("PO BOX 1309");
    obj.setVendorCityName("BATTLE CREEK");
    obj.setVendorStateCode("MI");
    obj.setVendorPostalCode("49016-1309");
    obj.setVendorCountryCode("US");
    obj.setAccountsPayableProcessorIdentifier("2133704704");
    obj.setLastActionPerformedByPersonId("2133704704");
    obj.setProcessingCampusCode("IN");
    obj.setAccountsPayableApprovalTimestamp(timeStamp);
    obj.setOriginalVendorHeaderGeneratedIdentifier(2013);
    obj.setOriginalVendorDetailAssignedIdentifier(0);
    obj.setContinuationAccountIndicator(false);
    obj.setAccountsPayablePurchasingDocumentLinkIdentifier(21);
    obj.setClosePurchaseOrderIndicator(false);
    obj.setReopenPurchaseOrderIndicator(false);
    obj.setReceivingDocumentRequiredIndicator(false);
    obj.setPaymentRequestPositiveApprovalIndicator(false);
    obj.setUseTaxIndicator(true);
    obj.setDocumentHeader(FinancialSystemDocumentHeaderFixture.PREQ1.newRecord());
    return obj;
}
Example 17
Project: geotools-2.7.x-master  File: IngresDateTestSetup.java View source code
@Override
protected void createDateTable() throws Exception {
    Connection con = getDataSource().getConnection();
    con.prepareStatement("CREATE TABLE DATES (D ANSIDATE, DT TIMESTAMP, T TIME)").execute();
    PreparedStatement ps = con.prepareStatement("INSERT INTO DATES VALUES (?,?,?)");
    ps.setDate(1, java.sql.Date.valueOf("2009-06-28"));
    //ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-06-28 15:12:41.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("15:12:41,28-2009-06").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("15:12:41"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-01-15"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-01-15 13:10:12.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("13:10:12,15-2009-01").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("13:10:12"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-09-29"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-09-29 17:54:23.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("17:54:23,29-2009-09").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("17:54:23"));
    ps.execute();
    ps.close();
    con.close();
}
Example 18
Project: geotools-master  File: IngresDateTestSetup.java View source code
@Override
protected void createDateTable() throws Exception {
    Connection con = getDataSource().getConnection();
    con.prepareStatement("CREATE TABLE DATES (D ANSIDATE, DT TIMESTAMP, T TIME)").execute();
    PreparedStatement ps = con.prepareStatement("INSERT INTO DATES VALUES (?,?,?)");
    ps.setDate(1, java.sql.Date.valueOf("2009-06-28"));
    //ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-06-28 15:12:41.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("15:12:41,28-2009-06").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("15:12:41"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-01-15"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-01-15 13:10:12.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("13:10:12,15-2009-01").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("13:10:12"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-09-29"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-09-29 17:54:23.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("17:54:23,29-2009-09").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("17:54:23"));
    ps.execute();
    ps.close();
    con.close();
}
Example 19
Project: geotools-old-master  File: IngresDateTestSetup.java View source code
@Override
protected void createDateTable() throws Exception {
    Connection con = getDataSource().getConnection();
    con.prepareStatement("CREATE TABLE DATES (D ANSIDATE, DT TIMESTAMP, T TIME)").execute();
    PreparedStatement ps = con.prepareStatement("INSERT INTO DATES VALUES (?,?,?)");
    ps.setDate(1, java.sql.Date.valueOf("2009-06-28"));
    //ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-06-28 15:12:41.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("15:12:41,28-2009-06").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("15:12:41"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-01-15"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-01-15 13:10:12.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("13:10:12,15-2009-01").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("13:10:12"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-09-29"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-09-29 17:54:23.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("17:54:23,29-2009-09").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("17:54:23"));
    ps.execute();
    ps.close();
    con.close();
}
Example 20
Project: geotools_trunk-master  File: IngresDateTestSetup.java View source code
@Override
protected void createDateTable() throws Exception {
    Connection con = getDataSource().getConnection();
    con.prepareStatement("CREATE TABLE DATES (D ANSIDATE, DT TIMESTAMP, T TIME)").execute();
    PreparedStatement ps = con.prepareStatement("INSERT INTO DATES VALUES (?,?,?)");
    ps.setDate(1, java.sql.Date.valueOf("2009-06-28"));
    //ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-06-28 15:12:41.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("15:12:41,28-2009-06").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("15:12:41"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-01-15"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-01-15 13:10:12.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("13:10:12,15-2009-01").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("13:10:12"));
    ps.execute();
    ps.setDate(1, java.sql.Date.valueOf("2009-09-29"));
    //       ps.setTimestamp(2, java.sql.Timestamp.valueOf("2009-09-29 17:54:23.0"));
    ps.setTimestamp(2, new java.sql.Timestamp(new java.text.SimpleDateFormat("HH:mm:ss,dd-yyyy-MM").parse("17:54:23,29-2009-09").getTime()));
    ps.setTime(3, java.sql.Time.valueOf("17:54:23"));
    ps.execute();
    ps.close();
    con.close();
}
Example 21
Project: liquibase-master  File: ExecutedAfterChangeSetFilter.java View source code
@Override
public ChangeSetFilterResult accepts(ChangeSet changeSet) {
    if (changeLogsAfterDate.contains(changeLogToString(changeSet.getId(), changeSet.getAuthor(), changeSet.getFilePath()))) {
        return new ChangeSetFilterResult(true, "Change set ran after " + new ISODateFormat().format(new java.sql.Timestamp(date.getTime())), this.getClass());
    } else {
        return new ChangeSetFilterResult(false, "Change set ran before " + new ISODateFormat().format(new java.sql.Timestamp(date.getTime())), this.getClass());
    }
}
Example 22
Project: Question_Box_Desktop-master  File: Util.java View source code
/**
     * Converts date from String to sql timeStamp type using the default Format (EEE MMM dd H:mm:ss z yyyy).
     * @param DateString
     * @return java.sql.Timestamp
     * @throws Exception
     */
public static java.sql.Timestamp toTimestamp(String DateString) throws Exception {
    long longDate = (long) new Date().getTime();
    try {
        java.sql.Date sdt;
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd H:mm:ss z yyyy");
        java.util.Date udt = (java.util.Date) sdf.parse(DateString);
        longDate = (long) udt.UTC(udt.getYear(), udt.getMonth(), udt.getDate(), udt.getHours(), udt.getMinutes(), udt.getSeconds());
    } catch (ParseException e) {
        throw new Exception(e.getMessage());
    }
    return new java.sql.Timestamp(longDate);
}
Example 23
Project: tamper-master  File: DateAndSqlDateTest.java View source code
@Test
public void testDateAndSqlDate() {
    Calendar c1 = Calendar.getInstance();
    c1.set(2010, 10 - 1, 01, 23, 59, 59);
    c1.set(Calendar.MILLISECOND, 0);
    Date timeDate = c1.getTime();
    Convertor dateToSql = helper.getConvertor(Date.class, java.sql.Date.class);
    java.sql.Date sqlDate = (java.sql.Date) dateToSql.convert(timeDate, java.sql.Date.class);
    assertNotNull(sqlDate);
    java.sql.Time sqlTime = (java.sql.Time) dateToSql.convert(timeDate, java.sql.Time.class);
    assertNotNull(sqlTime);
    java.sql.Timestamp sqlTimestamp = (java.sql.Timestamp) dateToSql.convert(timeDate, java.sql.Timestamp.class);
    assertNotNull(sqlTimestamp);
    Convertor sqlToDate = helper.getConvertor(java.sql.Date.class, Date.class);
    Date date = (Date) sqlToDate.convert(sqlDate, Date.class);
    assertEquals(timeDate, date);
    date = (Date) sqlToDate.convert(sqlTime, Date.class);
    assertEquals(timeDate, date);
    date = (Date) sqlToDate.convert(sqlTimestamp, Date.class);
    assertEquals(timeDate, date);
}
Example 24
Project: tddl-master  File: LongAndDateConvertor.java View source code
@Override
public Object convert(Object src, Class destClass) {
    if (Long.class.isInstance(src)) {
        // 必须是Date类型
        Long time = (Long) src;
        // java.util.Date
        if (destClass.equals(java.util.Date.class)) {
            return new java.util.Date(time);
        }
        // java.sql.Date
        if (destClass.equals(java.sql.Date.class)) {
            return new java.sql.Date(time);
        }
        // java.sql.Time
        if (destClass.equals(java.sql.Time.class)) {
            return new java.sql.Time(time);
        }
        // java.sql.Timestamp
        if (destClass.equals(java.sql.Timestamp.class)) {
            return new java.sql.Timestamp(time);
        }
    }
    throw new ConvertorException("Unsupported convert: [" + src + "," + destClass.getName() + "]");
}
Example 25
Project: com.idega.block.text-master  File: LocalizedTextBMPBean.java View source code
public void initializeAttributes() {
    addAttribute(getIDColumnName());
    addAttribute(getColumnNameLocaleId(), "Locale", true, true, java.lang.Integer.class, "many_to_one", com.idega.core.localisation.data.ICLocale.class);
    addAttribute(getColumnNameHeadline(), "Headline", true, true, java.lang.String.class);
    addAttribute(getColumnNameTitle(), "Title", true, true, java.lang.String.class);
    addAttribute(getColumnNameBody(), "Body", true, true, java.lang.String.class, 30000);
    addAttribute(getColumnNameCreated(), "Created", true, true, java.sql.Timestamp.class);
    addAttribute(getColumnNameUpdated(), "Updated", true, true, java.sql.Timestamp.class);
    addAttribute(getColumnNameMarkupLanguage(), "The markup language of the text", true, true, java.lang.String.class);
    addIndex("IDX_TX_LOCALIZED_TEXT_1", getColumnNameLocaleId());
}
Example 26
Project: platform2-master  File: RaindanceCheckHeaderBMPBean.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see com.idega.data.GenericEntity#initializeAttributes()
	 */
public void initializeAttributes() {
    addAttribute(getIDColumnName());
    addManyToOneRelationship(COLUMN_SCHOOL_CATEGORY, SchoolCategory.class);
    addAttribute(COLUMN_STATUS, "Key to localized status", true, true, java.lang.String.class);
    addAttribute(COLUMN_EVENT_DATE, "The date of the logged event", true, true, java.sql.Timestamp.class);
    addAttribute(COLUMN_EVENT_START_TIME, "The start time of the logged event", true, true, java.sql.Timestamp.class);
    addAttribute(COLUMN_EVENT_END_TIME, "The end time of the logged event", true, true, java.sql.Timestamp.class);
}
Example 27
Project: asakusafw-master  File: DateTimeOptionInspector.java View source code
@Override
public java.sql.Timestamp getPrimitiveJavaObject(Object o) {
    DateTimeOption object = (DateTimeOption) o;
    if (object == null || object.isNull()) {
        return null;
    }
    DateTime value = object.get();
    // FIXME for optimization
    @SuppressWarnings("deprecation") java.sql.Timestamp result = new java.sql.Timestamp(value.getYear() - 1900, value.getMonth() - 1, value.getDay(), value.getHour(), value.getMinute(), value.getSecond(), 0);
    return result;
}
Example 28
Project: com.idega.core-master  File: ICBusinessBMPBean.java View source code
public void initializeAttributes() {
    addAttribute(getIDColumnName());
    addAttribute(getColumnName(), "Name", true, true, String.class);
    addAttribute(getColumnDescription(), "Description", true, true, String.class);
    addAttribute(getColumnType(), "Type", true, true, String.class);
    addAttribute(getColumnCreated(), "Created", true, true, java.sql.Timestamp.class);
    addAttribute(getColumnValid(), "Valid", true, true, Boolean.class);
}
Example 29
Project: compomics-utilities-master  File: TimestampRenderer.java View source code
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (value instanceof java.sql.Timestamp) {
        java.sql.Timestamp ts = (java.sql.Timestamp) value;
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        String text = sdf.format(ts);
        this.setText(text);
        if (table != null) {
            this.setFont(table.getFont());
        }
    } else {
        logger.error("Got a " + value.getClass().getName() + " for the renderer instead of a java.sql.Timestamp.");
    }
    if (isSelected) {
        this.setForeground(table.getSelectionForeground());
        this.setBackground(table.getSelectionBackground());
    } else {
        this.setForeground(table.getForeground());
        this.setBackground(table.getBackground());
    }
    if (hasFocus) {
        setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
    } else {
        setBorder(noFocusBorder);
    }
    return this;
}
Example 30
Project: zava-master  File: TimestampDeserializer.java View source code
@SuppressWarnings("unchecked")
protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {
    if (val == null) {
        return null;
    }
    if (val instanceof java.util.Date) {
        return (T) new java.sql.Timestamp(((Date) val).getTime());
    }
    if (val instanceof Number) {
        return (T) new java.sql.Timestamp(((Number) val).longValue());
    }
    if (val instanceof String) {
        String strVal = (String) val;
        if (strVal.length() == 0) {
            return null;
        }
        DateFormat dateFormat = parser.getDateFormat();
        try {
            Date date = (Date) dateFormat.parse(strVal);
            return (T) new Timestamp(date.getTime());
        } catch (ParseException e) {
        }
        long longVal = Long.parseLong(strVal);
        return (T) new java.sql.Timestamp(longVal);
    }
    throw new JSONException("parse error");
}
Example 31
Project: kairosdb-master  File: InsertDataPointQuery.java View source code
//---------------------------------------------------------------------------
//Deprecated
public int runUpdate(String metricId, java.sql.Timestamp timestamp, byte[] value) {
    int ret = 0;
    java.sql.PreparedStatement genorm_statement = null;
    try {
        String genorm_query = QUERY;
        genorm_statement = org.kairosdb.datastore.h2.orm.GenOrmDataSource.prepareStatement(genorm_query);
        genorm_statement.setString(1, metricId);
        genorm_statement.setTimestamp(2, timestamp);
        genorm_statement.setBytes(3, value);
        ret = genorm_statement.executeUpdate();
    } catch (java.sql.SQLException sqle) {
        throw new GenOrmException(sqle);
    } finally {
        try {
            if (genorm_statement != null)
                genorm_statement.close();
        } catch (java.sql.SQLException sqle2) {
        }
    }
    return (ret);
}
Example 32
Project: castor-master  File: StringToSqlTimestamp.java View source code
//-----------------------------------------------------------------------------------
/**
     * {@inheritDoc}
     */
public Object convert(final Object object) {
    long time;
    try {
        time = getCustomDateFormat().parse((String) object).getTime();
    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex.toString());
    }
    java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
    timestamp.setNanos((int) ((time % THOUSAND) * MILLION));
    //timestamp.setNanos(0);  // this can workaround the bug in SAP DB
    return timestamp;
}
Example 33
Project: geode-master  File: TemporalComparator.java View source code
// throws ClassCastExcepton if obj1 or obj2 is not a java.util.Date or subclass
public int compare(Object obj1, Object obj2) {
    java.util.Date date1 = (java.util.Date) obj1;
    java.util.Date date2 = (java.util.Date) obj2;
    long ms1 = date1.getTime();
    long ms2 = date2.getTime();
    // if we're dealing with Timestamps, then we need to extract milliseconds
    // out of the nanos and then do a compare with the "extra" nanos
    int extraNanos1 = 0;
    int extraNanos2 = 0;
    if (date1 instanceof java.sql.Timestamp) {
        int nanos = ((java.sql.Timestamp) date1).getNanos();
        int ms = nanos / 1000000;
        ms1 += ms;
        extraNanos1 = nanos - (ms * 1000000);
    }
    if (date2 instanceof java.sql.Timestamp) {
        int nanos = ((java.sql.Timestamp) date2).getNanos();
        int ms = nanos / 1000000;
        ms2 += ms;
        extraNanos2 = nanos - (ms * 1000000);
    }
    if (ms1 != ms2)
        return ms1 < ms2 ? -1 : 1;
    return extraNanos1 == extraNanos2 ? 0 : (extraNanos1 < extraNanos2 ? -1 : 1);
}
Example 34
Project: esup-helpdesk-master  File: StatisticsExtractorImpl.java View source code
/**
     * @see org.esupportail.helpdesk.services.statistics.StatisticsExtractor#getTicketCreationsByYear(
     * java.sql.Timestamp, java.sql.Timestamp, java.util.List, java.util.List)
     */
@Override
public Map<Timestamp, Integer> getTicketCreationsByYear(final Timestamp start, final Timestamp end, final List<Department> departments, final List<String> origins) {
    List<Timestamp> dates = getYearTimestamps(start, end);
    Map<Timestamp, Integer> result = emptyTimestampIntegerMap();
    List<YearTicketCreationStatistic> stats = getDaoService().getTicketCreationsByYear(start, end, StatisticsExtractor.GLOBAL, departments, origins);
    for (YearTicketCreationStatistic stat : stats) {
        result.put(StatisticsUtils.getYearDate(stat.getYear()), stat.getNumber());
    }
    fillMissingTimestampIntegerMap(dates, result);
    return result;
}
Example 35
Project: dhcp-master  File: JdbcIaPrefixDAO.java View source code
@Override
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
    PreparedStatement ps = conn.prepareStatement("insert into iaprefix" + " (prefixaddress, prefixlength, starttime, preferredendtime," + " validendtime, state, identityassoc_id)" + " values (?, ?, ?, ?, ?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS);
    ps.setBytes(1, iaPrefix.getIpAddress().getAddress());
    ps.setInt(2, iaPrefix.getPrefixLength());
    java.sql.Timestamp sts = new java.sql.Timestamp(iaPrefix.getStartTime().getTime());
    ps.setTimestamp(3, sts, Util.GMT_CALENDAR);
    java.sql.Timestamp pts = new java.sql.Timestamp(iaPrefix.getPreferredEndTime().getTime());
    ps.setTimestamp(4, pts, Util.GMT_CALENDAR);
    java.sql.Timestamp vts = new java.sql.Timestamp(iaPrefix.getValidEndTime().getTime());
    ps.setTimestamp(5, vts, Util.GMT_CALENDAR);
    ps.setByte(6, iaPrefix.getState());
    ps.setLong(7, iaPrefix.getIdentityAssocId());
    return ps;
}
Example 36
Project: jadira-master  File: TimestampColumnTimestampMapper.java View source code
@Override
public String toNonNullString(java.sql.Timestamp value) {
    TimeZone gmtZone = TimeZone.getTimeZone("GMT");
    final SimpleDateFormat sdf = DATETIME_FORMAT.get();
    sdf.setTimeZone(gmtZone);
    Calendar now = Calendar.getInstance(gmtZone);
    now.clear();
    now.setTime(value);
    final String tsString;
    long milliseconds = now.get(Calendar.MILLISECOND);
    if (milliseconds > 0) {
        tsString = sdf.format(value);
    } else {
        String nanosString = "" + milliseconds + "000000000";
        nanosString = nanosString.substring(0, 9);
        tsString = sdf.format(value) + "." + nanosString;
    }
    return tsString;
}
Example 37
Project: spearal-java-master  File: TestDateTime.java View source code
@Test
public void test() throws IOException {
    encodeDecode(new Date(), -1);
    encodeDecode(new Date(0L), -1);
    encodeDecode(new Date(Long.MAX_VALUE), -1);
    encodeDecode(new java.sql.Date(new Date().getTime()), -1);
    encodeDecode(new java.sql.Date(0L), -1);
    encodeDecode(new java.sql.Date(Long.MAX_VALUE), -1);
    encodeDecode(new java.sql.Time(new Date().getTime()), -1);
    encodeDecode(new java.sql.Time(0L), -1);
    encodeDecode(new java.sql.Time(Long.MAX_VALUE), -1);
    encodeDecode(new java.sql.Timestamp(new Date().getTime()), -1);
    encodeDecode(new java.sql.Timestamp(0L), -1);
    encodeDecode(new java.sql.Timestamp(Long.MAX_VALUE), -1);
    java.sql.Timestamp ts = new java.sql.Timestamp(new Date().getTime());
    ts.setNanos(999999999);
    encodeDecode(ts, -1);
    encodeDecode(Calendar.getInstance(UTC), -1);
}
Example 38
Project: hospitalcore-master  File: DateUtils.java View source code
public static java.sql.Timestamp String2Timestamp(String strInputDate) {
    String strDate = strInputDate;
    int i, nYear, nMonth, nDay;
    String strSub = null;
    i = strDate.indexOf("/");
    if (i < 0) {
        return createTimestamp();
    }
    strSub = strDate.substring(0, i);
    nDay = (new Integer(strSub.trim())).intValue();
    strDate = strDate.substring(i + 1);
    i = strDate.indexOf("/");
    if (i < 0) {
        return createTimestamp();
    }
    strSub = strDate.substring(0, i);
    // Month begin from 0 value
    nMonth = (new Integer(strSub.trim())).intValue() - 1;
    strDate = strDate.substring(i + 1);
    if (strDate.length() < 4) {
        if (strDate.substring(0, 1).equals("9")) {
            strDate = "19" + strDate.trim();
        } else {
            strDate = "20" + strDate.trim();
        }
    }
    nYear = (new Integer(strDate)).intValue();
    java.util.Calendar calendar = java.util.Calendar.getInstance();
    calendar.set(nYear, nMonth, nDay);
    return new java.sql.Timestamp((calendar.getTime()).getTime());
}
Example 39
Project: SDMXHDataExport-master  File: DateUtils.java View source code
public static java.sql.Timestamp String2Timestamp(String strInputDate) {
    String strDate = strInputDate;
    int i, nYear, nMonth, nDay;
    String strSub = null;
    i = strDate.indexOf("/");
    if (i < 0) {
        return createTimestamp();
    }
    strSub = strDate.substring(0, i);
    nDay = (new Integer(strSub.trim())).intValue();
    strDate = strDate.substring(i + 1);
    i = strDate.indexOf("/");
    if (i < 0) {
        return createTimestamp();
    }
    strSub = strDate.substring(0, i);
    // Month begin from 0 value
    nMonth = (new Integer(strSub.trim())).intValue() - 1;
    strDate = strDate.substring(i + 1);
    if (strDate.length() < 4) {
        if (strDate.substring(0, 1).equals("9")) {
            strDate = "19" + strDate.trim();
        } else {
            strDate = "20" + strDate.trim();
        }
    }
    nYear = (new Integer(strDate)).intValue();
    java.util.Calendar calendar = java.util.Calendar.getInstance();
    calendar.set(nYear, nMonth, nDay);
    return new java.sql.Timestamp((calendar.getTime()).getTime());
}
Example 40
Project: BACKUP_FROM_SVN-master  File: DateTimeType.java View source code
@Override
public String convertObjectToString(Object value, Database database) {
    if (value == null) {
        return null;
    } else if (value.toString().equalsIgnoreCase("null")) {
        return "null";
    } else if (value.toString().equals("CURRENT_TIMESTAMP()")) {
        return database.getCurrentDateTimeFunction();
    } else if (value instanceof DatabaseFunction) {
        return ((DatabaseFunction) value).getValue();
    } else if (database.getDatabaseFunctions().contains(new DatabaseFunction(value.toString()))) {
        return value.toString();
    } else if (value instanceof String) {
        return "'" + ((String) value).replaceAll("'", "''") + "'";
    }
    return database.getDateTimeLiteral(((java.sql.Timestamp) value));
}
Example 41
Project: jspxcms304-master  File: DateEditor.java View source code
public static Date parse(String text) {
    if (StringUtils.isBlank(text)) {
        // Treat empty String as null value.
        return null;
    }
    DateTime dt = DateTime.parse(text);
    if (text.length() > 10) {
        return new java.sql.Timestamp(dt.getMillis());
    } else {
        return new java.sql.Date(dt.getMillis());
    }
}
Example 42
Project: NemoVelo-master  File: Helper.java View source code
/**
	 * calculate difference between duration to calc overtime and min time for a
	 * location
	 *
	 * @param t1 start date
	 * @param t2 end date
	 * @param unit hour, day ... for DataBaseElements.PriceDurationUnit
	 * @return int
	 */
public static int getDifference(Timestamp t1, Timestamp t2, String unit) {
    int result;
    double unitDivision = -1;
    switch(unit) {
        case DataBaseElements.PriceDurationUnit.HOUR:
            unitDivision = 3600;
            break;
        case DataBaseElements.PriceDurationUnit.MINUTE:
            unitDivision = 60;
            break;
        case DataBaseElements.PriceDurationUnit.DAY:
            unitDivision = 86400;
            break;
        case DataBaseElements.PriceDurationUnit.MONTH:
            unitDivision = 2629743.83;
            break;
        case DataBaseElements.PriceDurationUnit.WEEK:
            unitDivision = 604800;
            break;
    }
    long nano1 = t1.getTime();
    long nano2 = t2.getTime();
    long difference = (nano2 - nano1);
    long differenceInSec = difference / 1000;
    float restInDivision = (float) (differenceInSec % unitDivision);
    result = (int) ((differenceInSec - restInDivision) / unitDivision);
    if (restInDivision > 0) {
        result++;
    }
    return result;
}
Example 43
Project: opencit-master  File: DateArgument.java View source code
@Override
public Argument build(Class<?> type, final Date value, StatementContext ctx) {
    return new Argument() {

        @Override
        public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
            statement.setTimestamp(position, new Timestamp(value.getTime()));
        }

        @Override
        public String toString() {
            return value.toString();
        }
    };
}
Example 44
Project: osgi-bundles-liquibase-master  File: DateTimeType.java View source code
@Override
public String convertObjectToString(Object value, Database database) {
    if (value == null) {
        return null;
    } else if (value.toString().equalsIgnoreCase("null")) {
        return "null";
    } else if (value.toString().equals("CURRENT_TIMESTAMP()")) {
        return database.getCurrentDateTimeFunction();
    } else if (value instanceof DatabaseFunction) {
        return ((DatabaseFunction) value).getValue();
    } else if (database.getDatabaseFunctions().contains(new DatabaseFunction(value.toString()))) {
        return value.toString();
    } else if (value instanceof String) {
        return "'" + ((String) value).replaceAll("'", "''") + "'";
    }
    return database.getDateTimeLiteral(((java.sql.Timestamp) value));
}
Example 45
Project: siu-master  File: DateTimeType.java View source code
@Override
public String convertObjectToString(Object value, Database database) {
    if (value == null) {
        return null;
    } else if (value.toString().equalsIgnoreCase("null")) {
        return "null";
    } else if (value.toString().equals("CURRENT_TIMESTAMP()")) {
        return database.getCurrentDateTimeFunction();
    } else if (value instanceof DatabaseFunction) {
        return ((DatabaseFunction) value).getValue();
    } else if (database.getDatabaseFunctions().contains(new DatabaseFunction(value.toString()))) {
        return value.toString();
    } else if (value instanceof String) {
        return "'" + ((String) value).replaceAll("'", "''") + "'";
    }
    return database.getDateTimeLiteral(((java.sql.Timestamp) value));
}
Example 46
Project: cloudpier-core-master  File: MonitoringStatisticRepository.java View source code
public List<MonitoringStatistic> retrieveAllInRangeLimited(IMonitoringJob monitoringJob, Date start, Date end, int limit) {
    if (monitoringJob == null) {
        throw new RuntimeException("MonitoringJob can not be NULL!");
    }
    java.sql.Timestamp sqlStart = new java.sql.Timestamp(start.getTime());
    java.sql.Timestamp sqlEnd = new java.sql.Timestamp(end.getTime());
    String queryString = String.format("from MonitoringStatistic WHERE monitoringJobId = :monitoringJobId AND date >= :start AND date <= :end ORDER BY date DESC");
    System.out.println(sqlStart);
    System.out.println(sqlEnd);
    Query query = getSession().createQuery(queryString).setParameter("monitoringJobId", monitoringJob.getId()).setTimestamp("start", sqlStart).setTimestamp("end", sqlEnd).setMaxResults(limit);
    System.out.println(queryString.toString());
    @SuppressWarnings("unchecked") List<MonitoringStatistic> resultSet = ((List<MonitoringStatistic>) query.list());
    return resultSet;
}
Example 47
Project: funiture-master  File: LogConvert.java View source code
public static LogSearchDto of(LogPara para) {
    LogSearchDto dto = LogSearchDto.builder().type(para.getType()).beforeSeg(para.getBeforeSeg()).afterSeg(para.getAfterSeg()).targetId(para.getTargetId()).operator(para.getOperator()).fromTime(Timestamp.valueOf(para.getFromTime())).toTime(Timestamp.valueOf(para.getToTime())).build();
    return dto;
}
Example 48
Project: janala2-gradle-master  File: ObjectFactory.java View source code
public static ObjectValue create(int nFields, String className) {
    if (className.equals("java.lang.Integer")) {
        return new IntegerObjectValue();
    } else if (className.equals("java.lang.Long")) {
        return new LongObjectValue();
    } else if (className.equals("java.sql.Date") || className.equals("java.sql.Time") || className.equals("java.sql.Timestamp") || className.equals("java.util.Date")) {
        return new SqlDateObjectValue();
    }
    return new ObjectValue(nFields);
}
Example 49
Project: janala2-master  File: ObjectFactory.java View source code
public static ObjectValue create(int nFields, String className) {
    if (className.equals("java.lang.Integer")) {
        return new IntegerObjectValue();
    } else if (className.equals("java.lang.Long")) {
        return new LongObjectValue();
    } else if (className.equals("java.sql.Date") || className.equals("java.sql.Time") || className.equals("java.sql.Timestamp") || className.equals("java.util.Date")) {
        return new SqlDateObjectValue();
    }
    return new ObjectValue(nFields);
}
Example 50
Project: jfinal-rest-master  File: Interceptor.java View source code
public void intercept(Invocation ai) {
    long start = System.currentTimeMillis();
    ai.invoke();
    long end = System.currentTimeMillis();
    LOG.info("[" + new Timestamp(start) + "] Call method " + ai.getController().getClass().getSimpleName() + "." + ai.getMethodName() + "(), view path '" + ai.getActionKey() + "' , cost  " + (end - start) + " ms.");
}
Example 51
Project: mule-in-action-2e-master  File: URLMetricsComponent.java View source code
Map<String, String> getData(String data) {
    Map<String, String> result = new HashMap<String, String>(5);
    result.put("CLIENT_ID", "1");
    result.put("AVG_RESPONSE_TIME", "0.95");
    result.put("MED_RESPONSE_TIME", "0.75");
    result.put("MAX_RESPONSE_TIME", "0.195");
    Timestamp ts = new Timestamp(new Date().getTime());
    result.put("TIMESTAMP", ts.toString());
    return result;
}
Example 52
Project: oreva-master  File: TypeConverterTest.java View source code
@Test
public void testTemporalTypes() throws ParseException {
    DateFormat dateTimeParser = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.US);
    DateFormat timeParser = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.US);
    Calendar cal = Calendar.getInstance();
    Assert.assertEquals(dateTimeParser.parse("03/28/2011 7:20:21 pm"), TypeConverter.convert(new LocalDateTime(2011, 03, 28, 19, 20, 21), Date.class));
    Assert.assertEquals(timeParser.parse("7:20:21 pm"), TypeConverter.convert(new LocalTime(19, 20, 21), Date.class));
    cal.setTime(dateTimeParser.parse("03/28/2011 7:20:21 pm"));
    Assert.assertEquals(cal, TypeConverter.convert(new LocalDateTime(2011, 03, 28, 19, 20, 21), Calendar.class));
    cal.setTime(timeParser.parse("7:20:21 pm"));
    Assert.assertEquals(cal, TypeConverter.convert(new LocalTime(19, 20, 21), Calendar.class));
    Assert.assertEquals(new java.sql.Time(timeParser.parse("7:20:21 pm").getTime()), TypeConverter.convert(new LocalDateTime(1970, 1, 1, 19, 20, 21), java.sql.Time.class));
    Assert.assertEquals(new java.sql.Time(timeParser.parse("7:20:21 pm").getTime()), TypeConverter.convert(new LocalTime(19, 20, 21), java.sql.Time.class));
    Assert.assertEquals(new java.sql.Date(dateTimeParser.parse("03/28/2011 0:00:00 am").getTime()), TypeConverter.convert(new LocalDateTime(2011, 03, 28, 0, 0), java.sql.Date.class));
    Assert.assertEquals(new java.sql.Timestamp(dateTimeParser.parse("03/28/2011 7:20:21 pm").getTime()), TypeConverter.convert(new LocalDateTime(2011, 03, 28, 19, 20, 21), java.sql.Timestamp.class));
    Assert.assertEquals(new java.sql.Timestamp(timeParser.parse("7:20:21 pm").getTime()), TypeConverter.convert(new LocalTime(19, 20, 21), java.sql.Timestamp.class));
}
Example 53
Project: rapid-framework-master  File: DateConvertUtilsTest.java View source code
public void testConvertString2Date() {
    java.util.Date d = DateConvertUtils.parse("1999-09-09", "yyyy-MM-dd", java.util.Date.class);
    Timestamp t = DateConvertUtils.parse("1999-09-09", "yyyy-MM-dd", Timestamp.class);
    java.sql.Date sd = DateConvertUtils.parse("1999-09-09", "yyyy-MM-dd", java.sql.Date.class);
    java.sql.Time st = DateConvertUtils.parse("1999-09-09", "yyyy-MM-dd", java.sql.Time.class);
}
Example 54
Project: scriptella-etl-master  File: TimestampValueFormatTest.java View source code
public void testParse() throws Exception {
    String dateStr = "2012-5-25 01:02:03";
    Date expectedDate = Timestamp.valueOf(dateStr);
    Date actualDate = new TimestampValueFormat().parse(dateStr);
    assertEquals(expectedDate, actualDate);
    //test malformed  values
    try {
        new TimestampValueFormat().parse("");
    } catch (IllegalArgumentException e) {
        System.out.println("Expected " + e);
    }
}
Example 55
Project: simplexml-master  File: TimestampTransformTest.java View source code
public void testTimestamp() throws Exception {
    long now = System.currentTimeMillis();
    Timestamp date = new Timestamp(now);
    DateTransform format = new DateTransform(Timestamp.class);
    String value = format.write(date);
    Date copy = format.read(value);
    assertEquals(date, copy);
    assertEquals(copy.getTime(), now);
    assertTrue(copy instanceof Timestamp);
}
Example 56
Project: streetlights-master  File: TimestampTransformTest.java View source code
public void testTimestamp() throws Exception {
    long now = System.currentTimeMillis();
    Timestamp date = new Timestamp(now);
    DateTransform format = new DateTransform(Timestamp.class);
    String value = format.write(date);
    Date copy = format.read(value);
    assertEquals(date, copy);
    assertEquals(copy.getTime(), now);
    assertTrue(copy instanceof Timestamp);
}
Example 57
Project: zstack-master  File: APILogInReply.java View source code
public static APILogInReply __example__() {
    APILogInReply reply = new APILogInReply();
    SessionInventory inventory = new SessionInventory();
    inventory.setUuid(uuid());
    inventory.setAccountUuid(uuid());
    inventory.setExpiredDate(new Timestamp(new Date().getTime()));
    reply.setInventory(inventory);
    return reply;
}
Example 58
Project: reflectutils-master  File: DateConverter.java View source code
/**
     * @param <T>
     * @param targetType the type to convert to (should be one of the given date types)
     * @param value any object
     * @param dateFormats include date formats to use during the string -> date conversion
     * @return the converted value
     */
@SuppressWarnings("unchecked")
public static <T> T convertToType(Class<T> targetType, Object value, DateFormat[] dateFormats) {
    if (value == null) {
        throw new IllegalArgumentException("value to convert cannot be null");
    }
    // Handle java.sql.Timestamp
    if (value instanceof java.sql.Timestamp) {
        long timeInMillis = ((Timestamp) value).getTime();
        // ---------------------- JDK 1.3 Fix ----------------------
        return (T) toDate(targetType, timeInMillis);
    }
    // Handle Date (includes java.sql.Date & java.sql.Time)
    if (value instanceof Date) {
        long time = ((Date) value).getTime();
        return (T) toDate(targetType, time);
    }
    // Handle Calendar
    if (value instanceof Calendar) {
        long time = ((Calendar) value).getTimeInMillis();
        return (T) toDate(targetType, time);
    }
    // Handle numbers
    if (value instanceof Number) {
        long num = ((Number) value).longValue();
        return (T) toDate(targetType, num);
    }
    // Convert all other types to String & handle
    String stringValue = value.toString().trim();
    if (stringValue.length() == 0) {
        Object defaultValue = ConstructorUtils.getDefaultValue(targetType);
        if (defaultValue == null) {
            throw new UnsupportedOperationException("Date convert failure: Could not convert empty string to target (" + targetType + ") or get a default value for it");
        }
        return (T) defaultValue;
    } else {
        // try to get the long value out of the string
        try {
            long num = new Long(stringValue);
            if (num > 30000000l) {
                // must be a UTC time code, also, we only lost a week since 1970 so whatever
                return (T) toDate(targetType, num);
            } else if (num > 10000l) {
                // probably is a date like: YYYYMMDD so convert it
                int date = (int) (num % 100);
                int remain = (int) (num / 100);
                int month = remain % 100;
                int year = remain / 100;
                if (date <= 31 && month <= 12) {
                    if (month > 0) {
                        month -= 1;
                    }
                    Calendar calendar = Calendar.getInstance();
                    calendar.clear();
                    calendar.set(year, month, date);
                    long time = calendar.getTimeInMillis();
                    return (T) toDate(targetType, time);
                }
            }
        } catch (NumberFormatException e) {
        }
    }
    // Parse the Date/Time
    Calendar calendar = parse(stringValue, dateFormats);
    if (calendar != null) {
        long time = ((Calendar) value).getTimeInMillis();
        return (T) toDate(targetType, time);
    }
    // Default String conversion
    return (T) toDate(targetType, stringValue);
}
Example 59
Project: hibernate-orm-master  File: CalendarTimeTypeDescriptor.java View source code
@SuppressWarnings({ "unchecked" })
public <X> X unwrap(Calendar value, Class<X> type, WrapperOptions options) {
    if (value == null) {
        return null;
    }
    if (Calendar.class.isAssignableFrom(type)) {
        return (X) value;
    }
    if (java.sql.Date.class.isAssignableFrom(type)) {
        return (X) new java.sql.Date(value.getTimeInMillis());
    }
    if (java.sql.Time.class.isAssignableFrom(type)) {
        return (X) new java.sql.Time(value.getTimeInMillis());
    }
    if (java.sql.Timestamp.class.isAssignableFrom(type)) {
        return (X) new java.sql.Timestamp(value.getTimeInMillis());
    }
    if (Date.class.isAssignableFrom(type)) {
        return (X) new Date(value.getTimeInMillis());
    }
    throw unknownUnwrap(type);
}
Example 60
Project: Squeaky-master  File: TimeStampTypeTest.java View source code
@Test
public void testTimeStamp() throws Exception {
    Class<LocalTimeStamp> clazz = LocalTimeStamp.class;
    Dao<LocalTimeStamp> dao = helper.getDao(clazz);
    GregorianCalendar c = new GregorianCalendar();
    c.set(GregorianCalendar.MILLISECOND, 0);
    long millis = c.getTimeInMillis();
    java.sql.Timestamp val = new java.sql.Timestamp(millis);
    String format = "yyyy-MM-dd HH:mm:ss.SSSSSS";
    DateFormat dateFormat = new SimpleDateFormat(format);
    String valStr = dateFormat.format(val);
    LocalTimeStamp foo = new LocalTimeStamp();
    foo.timestamp = val;
    dao.create(foo);
    assertTrue(EqualsBuilder.reflectionEquals(foo, dao.queryForAll().list().get(0)));
}
Example 61
Project: StreamCruncher-master  File: OutOfOrderEventTest.java View source code
@Override
protected void verify(List<BatchResult> results) {
    long[] idOrder = { 1, 2, 3, 4, 7, 5, 6, 8, 9, 10, 11, 12, 13, 14 };
    LinkedHashMap<Long, Long> ids = new LinkedHashMap<Long, Long>();
    System.out.println("--Results--");
    for (BatchResult result : results) {
        System.out.println("Batch created at: " + new Timestamp(result.getTimestamp()) + ". Rows: " + result.getRows().size());
        List<Object[]> rows = result.getRows();
        System.out.println(" Batch results");
        for (Object[] objects : rows) {
            System.out.print(" ");
            for (Object object : objects) {
                System.out.print(object + " ");
            }
            /*
                 * "levela", "levelb", "event_time", "event_id", "curr_time".
                 */
            String levela = (String) objects[0];
            Double levelb = (Double) objects[1];
            long eventId = (Long) objects[3];
            Timestamp inputTime = (Timestamp) objects[2];
            Timestamp outputTime = (Timestamp) objects[4];
            long diff = outputTime.getTime() - inputTime.getTime();
            ids.put(eventId, diff);
            System.out.println();
        }
    }
    System.out.println("Received Ids: " + ids);
    int time = (windowSeconds * 1000) + /*
         * Extra time, just in case; because the original timestamps were
         * hardcoded.
         */
    1000;
    for (int i = 0; i < idOrder.length; i++) {
        Assert.assertTrue(ids.containsKey(idOrder[i]), "Results missing");
        Assert.assertFalse(ids.get(idOrder[i]) > time, "Event was allowed to stay for longer than " + time + " seconds");
    }
    int i = 0;
    for (Long l : ids.keySet()) {
        i++;
    }
}
Example 62
Project: wabacus-master  File: TimestampType.java View source code
public Object label2value(String label) {
    if (label == null || label.trim().equals(""))
        return null;
    try {
        Date date = new SimpleDateFormat(dateformat).parse(label.trim());
        return new java.sql.Timestamp(date.getTime());
    } catch (ParseException e) {
        log.error(label + "�法的日期格�,�能格�化为" + dateformat + "形�的日期类型", e);
        return null;
    }
}
Example 63
Project: QuickCached-master  File: H2CacheImpl.java View source code
public void setToCache(String key, Object value, int objectSize, int expInSec) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    java.sql.Timestamp currentTime = new java.sql.Timestamp(System.currentTimeMillis());
    java.sql.Timestamp expTime = null;
    if (expInSec != 0) {
        expTime = new java.sql.Timestamp(System.currentTimeMillis() + expInSec * 1000);
    }
    try {
        con = getConnection();
        pstmt = con.prepareStatement("INSERT INTO DATA_CACHE (KEY, DATA, SIZE, CREATION_TIME_STAMP, EXPIRY_TIME_STAMP, LAST_ACCESS_TIME) values(?,?,?,?,?,?)");
        int k = 1;
        pstmt.setString(k++, key);
        pstmt.setObject(k++, value);
        pstmt.setInt(k++, objectSize);
        pstmt.setTimestamp(k++, currentTime);
        pstmt.setTimestamp(k++, expTime);
        pstmt.setTimestamp(k++, currentTime);
        pstmt.executeUpdate();
    } catch (Exception e) {
        if (e.getMessage().startsWith("Unique index or primary key violation:")) {
            try {
                pstmt = con.prepareStatement("UPDATE DATA_CACHE SET DATA=?, SIZE=?, CREATION_TIME_STAMP=?, EXPIRY_TIME_STAMP=?, LAST_ACCESS_TIME=? WHERE KEY=?");
                int k = 1;
                pstmt.setObject(k++, value);
                pstmt.setInt(k++, objectSize);
                pstmt.setTimestamp(k++, currentTime);
                pstmt.setTimestamp(k++, expTime);
                pstmt.setTimestamp(k++, currentTime);
                pstmt.setString(k++, key);
                pstmt.executeUpdate();
            } catch (Exception er) {
                logger.log(Level.WARNING, "Update Error: " + er, er);
                throw er;
            }
        } else {
            logger.log(Level.WARNING, "Error: " + e, e);
            throw e;
        }
    } finally {
        try {
            pstmt.close();
        } catch (SQLException e1) {
            logger.log(Level.WARNING, "Error: " + e1, e1);
        }
        try {
            con.close();
        } catch (SQLException e1) {
            logger.log(Level.WARNING, "Error: " + e1, e1);
        }
    }
}
Example 64
Project: bboss-master  File: TestValueObjectUtil.java View source code
@org.junit.Test
public void testLongtoDate() {
    System.out.println(ValueObjectUtil.typeCast(new java.util.Date().getTime(), java.util.Date.class));
    System.out.println(ValueObjectUtil.typeCast(new java.util.Date().getTime(), java.sql.Date.class));
    System.out.println(ValueObjectUtil.typeCast(new java.util.Date().getTime(), java.sql.Timestamp.class));
}
Example 65
Project: ofbiz-master  File: DateTimeConverters.java View source code
public java.sql.Timestamp convert(String obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
    String str = obj.trim();
    if (str.length() == 0) {
        return null;
    }
    DateFormat df = null;
    if (UtilValidate.isEmpty(formatString)) {
        // for backward compatibility.
        if (str.length() > 0 && !str.contains(":")) {
            str = str + " 00:00:00.00";
        }
        // hack to mimic Timestamp.valueOf() method
        if (str.length() > 0 && !str.contains(".")) {
            str = str + ".0";
        } else {
            // DateFormat has a funny way of parsing milliseconds:
            // 00:00:00.2 parses to 00:00:00.002
            // so we'll add zeros to the end to get 00:00:00.200
            String[] timeSplit = str.split("[.]");
            if (timeSplit.length > 1 && timeSplit[1].length() < 3) {
                str = str + "000".substring(timeSplit[1].length());
            }
        }
        df = UtilDateTime.toDateTimeFormat(UtilDateTime.getDateTimeFormat(), timeZone, locale);
    } else {
        df = UtilDateTime.toDateTimeFormat(formatString, timeZone, locale);
    }
    try {
        return new java.sql.Timestamp(df.parse(str).getTime());
    } catch (ParseException e) {
        df = DateFormat.getDateTimeInstance();
        if (timeZone != null) {
            df.setTimeZone(timeZone);
        }
        try {
            return new java.sql.Timestamp(df.parse(str).getTime());
        } catch (ParseException e2) {
            throw new ConversionException(e);
        }
    }
}
Example 66
Project: gwt-jackson-master  File: DateOptionsTester.java View source code
public void testSerializeDatesAsTimestamps(ObjectWriterTester<BeanWithDates> writer) {
    BeanWithDates bean = new BeanWithDates();
    bean.date = new Date(1345304756540l);
    bean.onlyDate = new Date(1345304756540l);
    bean.onlyDateTz = new Date(1345304756540l);
    bean.sqlDate = new java.sql.Date(1345304756541l);
    bean.sqlTime = new Time(1345304756542l);
    bean.sqlTimestamp = new Timestamp(1345304756543l);
    Map<Date, String> mapDate = new HashMap<Date, String>();
    mapDate.put(new Date(1345304756544l), "java.util.Date");
    bean.mapDate = mapDate;
    Map<java.sql.Date, String> mapSqlDate = new HashMap<java.sql.Date, String>();
    mapSqlDate.put(new java.sql.Date(1345304756545l), "java.sql.Date");
    bean.mapSqlDate = mapSqlDate;
    Map<Time, String> mapSqlTime = new HashMap<Time, String>();
    mapSqlTime.put(new Time(1345304756546l), "java.sql.Time");
    bean.mapSqlTime = mapSqlTime;
    Map<Timestamp, String> mapSqlTimestamp = new HashMap<Timestamp, String>();
    mapSqlTimestamp.put(new Timestamp(1345304756547l), "java.sql.Timestamp");
    bean.mapSqlTimestamp = mapSqlTimestamp;
    String expected = "{" + "\"date\":1345304756540," + "\"onlyDate\":\"/2012/08/18/\"," + "\"onlyDateTz\":\"/2012/08/18/ +0000\"," + "\"sqlDate\":\"" + bean.sqlDate.toString() + "\"," + "\"sqlTime\":\"" + bean.sqlTime.toString() + "\"," + "\"sqlTimestamp\":1345304756543," + "\"mapDate\":{\"1345304756544\":\"java.util.Date\"}," + "\"mapSqlDate\":{\"1345304756545\":\"java.sql.Date\"}," + "\"mapSqlTime\":{\"1345304756546\":\"java.sql.Time\"}," + "\"mapSqlTimestamp\":{\"1345304756547\":\"java.sql.Timestamp\"}" + "}";
    assertEquals(expected, writer.write(bean));
}
Example 67
Project: oswing-master  File: GanttFrame.java View source code
/**
         * Method invoked by the grid to load all rows.
         * @param params gantt parameters
         * @return response from the server: an object of type VOListResponse if data loading was successfully completed, or an ErrorResponse onject if some error occours
         */
public Response loadData(Map params) {
    ArrayList list = new ArrayList();
    GanttWorkingHoursVO whVO = new GanttWorkingHoursVO();
    Calendar cal = Calendar.getInstance();
    cal.set(cal.HOUR_OF_DAY, 8);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    whVO.setMorningStartHour(new java.sql.Timestamp(cal.getTimeInMillis()));
    cal.set(cal.HOUR_OF_DAY, 12);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    whVO.setMorningEndHour(new java.sql.Timestamp(cal.getTimeInMillis()));
    cal.set(cal.HOUR_OF_DAY, 13);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    whVO.setAfternoonStartHour(new java.sql.Timestamp(cal.getTimeInMillis()));
    cal.set(cal.HOUR_OF_DAY, 17);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    whVO.setAfternoonEndHour(new java.sql.Timestamp(cal.getTimeInMillis()));
    HashSet set = new HashSet();
    AppointmentVO appVO = new AppointmentVO();
    appVO.setForegroundColor(Color.black);
    appVO.setDescription("job1");
    cal.set(cal.HOUR_OF_DAY, 8);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    appVO.setStartDate(new java.sql.Timestamp(cal.getTimeInMillis()));
    cal.set(cal.HOUR_OF_DAY, 12);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    appVO.setEndDate(new java.sql.Timestamp(cal.getTimeInMillis()));
    appVO.setEnableDelete(true);
    appVO.setEnableEdit(true);
    set.add(appVO);
    GanttRowVO vo = new GanttRowVO();
    vo.setAppointmentClass(AppointmentVO.class);
    vo.setLegend(new Object[] { "William Smith" });
    vo.setMondayWorkingHours(whVO);
    vo.setTuesdayWorkingHours(whVO);
    vo.setWednesdayWorkingHours(whVO);
    vo.setThursdayWorkingHours(whVO);
    vo.setFridayWorkingHours(whVO);
    vo.setSaturdayWorkingHours(whVO);
    vo.setSundayWorkingHours(whVO);
    vo.setAppointments(set);
    list.add(vo);
    set = new HashSet();
    appVO = new AppointmentVO();
    appVO.setForegroundColor(Color.lightGray);
    appVO.setDescription("job2");
    cal.set(cal.HOUR_OF_DAY, 0);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    appVO.setStartDate(new java.sql.Timestamp(cal.getTimeInMillis()));
    cal.set(cal.HOUR_OF_DAY, 24);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    appVO.setEndDate(new java.sql.Timestamp(cal.getTimeInMillis()));
    appVO.setEnableDelete(true);
    appVO.setEnableEdit(true);
    set.add(appVO);
    vo = new GanttRowVO();
    vo.setAppointmentClass(AppointmentVO.class);
    vo.setLegend(new Object[] { "John Doe" });
    vo.setMondayWorkingHours(whVO);
    vo.setTuesdayWorkingHours(whVO);
    vo.setWednesdayWorkingHours(whVO);
    vo.setThursdayWorkingHours(whVO);
    vo.setFridayWorkingHours(whVO);
    vo.setSaturdayWorkingHours(whVO);
    vo.setSundayWorkingHours(whVO);
    vo.setAppointments(set);
    list.add(vo);
    set = new HashSet();
    appVO = new AppointmentVO();
    appVO.setForegroundColor(Color.gray);
    appVO.setDescription("job3");
    cal.set(cal.HOUR_OF_DAY, 13);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    appVO.setStartDate(new java.sql.Timestamp(cal.getTimeInMillis()));
    cal.set(cal.DAY_OF_MONTH, cal.get(cal.DAY_OF_MONTH) + 2);
    cal.set(cal.HOUR_OF_DAY, 12);
    cal.set(cal.MINUTE, 0);
    cal.set(cal.SECOND, 0);
    cal.set(cal.MILLISECOND, 0);
    appVO.setEndDate(new java.sql.Timestamp(cal.getTimeInMillis()));
    appVO.setEnableDelete(true);
    appVO.setEnableEdit(true);
    set.add(appVO);
    vo = new GanttRowVO();
    vo.setAppointmentClass(AppointmentVO.class);
    vo.setLegend(new Object[] { "Frank Porter" });
    vo.setMondayWorkingHours(whVO);
    vo.setTuesdayWorkingHours(whVO);
    vo.setWednesdayWorkingHours(whVO);
    vo.setThursdayWorkingHours(whVO);
    vo.setFridayWorkingHours(whVO);
    vo.setSaturdayWorkingHours(whVO);
    vo.setSundayWorkingHours(whVO);
    vo.setAppointments(set);
    list.add(vo);
    return new VOListResponse(list, false, list.size());
}
Example 68
Project: oswregistrationplugin-master  File: DBManager.java View source code
public int createCode(String code, int duration, int total) throws SQLException {
    if ((connection == null) || (connection.isClosed()))
        connection = this.getConnection();
    if ((code == null) || (code.length() == 0))
        code = factory.code();
    long timeMilis = Calendar.getInstance().getTimeInMillis();
    java.sql.Timestamp sqlDateStart = new java.sql.Timestamp(timeMilis);
    String query = "INSERT INTO invitation(code, created, expires, total, used, valid) VALUES (?,?,?,?,?,?) ";
    PreparedStatement st = connection.prepareStatement(query);
    st.setString(1, code);
    st.setTimestamp(2, sqlDateStart);
    java.sql.Timestamp sqlDateExp = null;
    if (duration > 0) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DATE, duration);
        sqlDateExp = new java.sql.Timestamp(now.getTimeInMillis());
        st.setTimestamp(3, sqlDateExp);
    } else {
        st.setTimestamp(3, null);
    }
    st.setInt(4, total);
    st.setInt(5, 0);
    st.setBoolean(6, true);
    int i_code = st.executeUpdate();
    return i_code;
}
Example 69
Project: pgjdbc-master  File: TimestampTest.java View source code
/**
   * Ensure the driver doesn't modify a Calendar that is passed in.
   */
@Test
public void testCalendarModification() throws SQLException {
    Calendar cal = Calendar.getInstance();
    Calendar origCal = (Calendar) cal.clone();
    PreparedStatement ps = con.prepareStatement("INSERT INTO " + TSWOTZ_TABLE + " VALUES (?)");
    ps.setDate(1, new Date(0), cal);
    ps.executeUpdate();
    assertEquals(origCal, cal);
    ps.setTimestamp(1, new Timestamp(0), cal);
    ps.executeUpdate();
    assertEquals(origCal, cal);
    ps.setTime(1, new Time(0), cal);
    // Can't actually execute this one because of type mismatch,
    // but all we're really concerned about is the set call.
    // ps.executeUpdate();
    assertEquals(origCal, cal);
    ps.close();
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT ts FROM " + TSWOTZ_TABLE);
    assertTrue(rs.next());
    rs.getDate(1, cal);
    assertEquals(origCal, cal);
    rs.getTimestamp(1, cal);
    assertEquals(origCal, cal);
    rs.getTime(1, cal);
    assertEquals(origCal, cal);
    rs.close();
    stmt.close();
}
Example 70
Project: hibernate-semantic-query-master  File: JdbcTimeJavaDescriptor.java View source code
@SuppressWarnings({ "unchecked" })
@Override
public <X> X unwrap(Date value, Class<X> type, WrapperOptions options) {
    if (value == null) {
        return null;
    }
    if (Time.class.isAssignableFrom(type)) {
        final Time rtn = Time.class.isInstance(value) ? (Time) value : new Time(value.getTime());
        return (X) rtn;
    }
    if (java.sql.Date.class.isAssignableFrom(type)) {
        final java.sql.Date rtn = java.sql.Date.class.isInstance(value) ? (java.sql.Date) value : new java.sql.Date(value.getTime());
        return (X) rtn;
    }
    if (java.sql.Timestamp.class.isAssignableFrom(type)) {
        final java.sql.Timestamp rtn = java.sql.Timestamp.class.isInstance(value) ? (java.sql.Timestamp) value : new java.sql.Timestamp(value.getTime());
        return (X) rtn;
    }
    if (Date.class.isAssignableFrom(type)) {
        return (X) value;
    }
    if (Calendar.class.isAssignableFrom(type)) {
        final GregorianCalendar cal = new GregorianCalendar();
        cal.setTimeInMillis(value.getTime());
        return (X) cal;
    }
    if (Long.class.isAssignableFrom(type)) {
        return (X) Long.valueOf(value.getTime());
    }
    throw unknownUnwrap(type);
}
Example 71
Project: jdonframework-master  File: UtilDateTime.java View source code
public static java.sql.Timestamp getDayStart(java.sql.Timestamp stamp, int daysLater) {
    Calendar tempCal = Calendar.getInstance();
    tempCal.setTime(new java.util.Date(stamp.getTime()));
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    return new java.sql.Timestamp(tempCal.getTime().getTime());
}
Example 72
Project: otter-master  File: SqlTimestampConverter.java View source code
/**
     * Convert the specified input object into an output object of the specified type.
     * 
     * @param type Data type to which this value should be converted
     * @param value The input value to be converted
     * @exception ConversionException if conversion cannot be performed successfully
     */
public Object convert(Class type, Object value) {
    if (value == null) {
        if (useDefault) {
            return (defaultValue);
        } else {
            throw new ConversionException("No value specified");
        }
    }
    if (value instanceof java.sql.Date && java.sql.Date.class.equals(type)) {
        return value;
    } else if (value instanceof java.sql.Time && java.sql.Time.class.equals(type)) {
        return value;
    } else if (value instanceof java.sql.Timestamp && java.sql.Timestamp.class.equals(type)) {
        return value;
    } else {
        try {
            if (java.sql.Date.class.equals(type)) {
                return new java.sql.Date(convertTimestamp2TimeMillis(value.toString()));
            } else if (java.sql.Time.class.equals(type)) {
                return new java.sql.Time(convertTimestamp2TimeMillis(value.toString()));
            } else if (java.sql.Timestamp.class.equals(type)) {
                return new java.sql.Timestamp(convertTimestamp2TimeMillis(value.toString()));
            } else {
                return new Timestamp(convertTimestamp2TimeMillis(value.toString()));
            }
        } catch (Exception e) {
            throw new ConversionException("Value format invalid: " + e.getMessage(), e);
        }
    }
}
Example 73
Project: tizzit-master  File: DateConverter.java View source code
public static boolean isDateToday(java.sql.Timestamp date) {
    if (date == null)
        return false;
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.applyPattern("dd.MM.yyyy");
    String lDate = sdf.format(date);
    Date today = new Date(System.currentTimeMillis());
    String lToday = sdf.format(today);
    if (lDate.equals(lToday))
        return true;
    return false;
}
Example 74
Project: wonder-master  File: ValueFactory.java View source code
public static LocalDateTime localDateTime(Date value) {
    LocalDateTime ldt = null;
    if (value instanceof java.sql.Timestamp) {
        ldt = ((java.sql.Timestamp) value).toLocalDateTime();
    } else {
        throw new IllegalArgumentException("Expected java.sql.Timestamp object but got <" + value.getClass().getCanonicalName() + ">.");
    }
    return ldt;
}
Example 75
Project: li-old-master  File: ConvertTest.java View source code
@Test
public void timeConvert() {
    String[] times = { "2012/12/31 12:12:12", "2012-12-31 12:12:12", "2012/12/31 12:12", "2012-12-31 12:12", "2012/12/31", "2012-12-31", "12:12:12", "12:12" };
    Class<?>[] types = { java.util.Date.class, java.sql.Date.class, Time.class, Timestamp.class };
    for (String time : times) {
        for (Class<?> type : types) {
            log.debug(Convert.toType(type, time));
        }
    }
}
Example 76
Project: nextreports-server-master  File: TableObjectComparator.java View source code
public int compare(Object o1, Object o2) {
    if ((o1 == null) && (o2 == null)) {
        return 0;
    }
    if (o1 == null) {
        return -1;
    }
    if (o2 == null) {
        return 1;
    }
    if (!o1.getClass().equals(o2.getClass())) {
        return o1.getClass().toString().compareTo(o2.getClass().toString());
    }
    String className = o1.getClass().getName();
    if (className.equals("java.lang.String")) {
        return ((String) o1).compareTo((String) o2);
    } else if (className.equals("java.lang.Byte") || className.equals("byte")) {
        return ((Byte) o1).compareTo((Byte) o2);
    } else if (className.equals("java.lang.Short") || className.equals("short")) {
        return ((Short) o1).compareTo((Short) o2);
    } else if (className.equals("java.lang.Integer") || className.equals("int")) {
        return ((Integer) o1).compareTo((Integer) o2);
    } else if (className.equals("java.lang.Float") || className.equals("float")) {
        return ((Float) o1).compareTo((Float) o2);
    } else if (className.equals("java.lang.Double") || className.equals("double")) {
        return ((Double) o1).compareTo((Double) o2);
    } else if (className.equals("java.math.BigDecimal")) {
        return ((BigDecimal) o1).compareTo((BigDecimal) o2);
    } else if (className.equals("java.lang.BigInteger")) {
        return ((BigInteger) o1).compareTo((BigInteger) o2);
    } else if (className.equals("java.lang.Character") || className.equals("char")) {
        return ((Character) o1).compareTo((Character) o2);
    } else if (className.equals("java.lang.Boolean") || className.equals("boolean")) {
        return ((Boolean) o1).compareTo((Boolean) o2);
    } else if (className.equals("java.util.Date")) {
        return ((Date) o1).compareTo((Date) o2);
    } else if (className.equals("java.sql.Date")) {
        return ((java.sql.Date) o1).compareTo((java.sql.Date) o2);
    } else if (className.equals("java.sql.Timestamp")) {
        return ((java.sql.Timestamp) o1).compareTo((java.sql.Timestamp) o2);
    } else if (className.equals("java.sql.Time")) {
        return ((java.sql.Time) o1).compareTo((java.sql.Time) o2);
    }
    return o1.toString().compareTo(o2.toString());
}
Example 77
Project: OpenDolphin-master  File: BeanUtils.java View source code
public static byte[] xmlEncode(Object bean) {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    //masuda^   java.sql.Date�java.sql.Timestamp�xmlEncode�失敗�る
    try (XMLEncoder e = new XMLEncoder(new BufferedOutputStream(bo))) {
        //masuda^   java.sql.Date�java.sql.Timestamp�xmlEncode�失敗�る
        DatePersistenceDelegate dpd = new DatePersistenceDelegate();
        e.setPersistenceDelegate(java.sql.Date.class, dpd);
        TimestampPersistenceDelegate tpd = new TimestampPersistenceDelegate();
        e.setPersistenceDelegate(java.sql.Timestamp.class, tpd);
        //masuda$
        e.writeObject(bean);
    }
    return bo.toByteArray();
}
Example 78
Project: zk-master  File: DateFormatConverter.java View source code
/**
	 * Depending whether the data is coming from the database or coming from the datebox 
	 * we might be passed either a java.util.Date or a java.sql.Timestamp
	 * 
	 * @see org.zkoss.zkplus.databind.TypeConverter#coerceToUi(java.lang.Object, org.zkoss.zk.ui.Component)
	 */
public Object coerceToUi(Object val, org.zkoss.zk.ui.Component comp) {
    Date date = null;
    if (val instanceof Timestamp) {
        final Timestamp timestamp = (Timestamp) val;
        date = new Date(timestamp.getTime());
    } else if (val instanceof Date) {
        date = (Date) val;
    }
    final Annotation annot = ((ComponentCtrl) comp).getAnnotation(null, "format");
    String pattern = null;
    if (annot != null) {
        pattern = annot.getAttribute("value");
    }
    if (date == null)
        return "";
    //prepare dateFormat and convert Date to String
    final SimpleDateFormat df = new SimpleDateFormat(pattern == null ? "MM/dd/yyyy" : pattern, Locales.getCurrent());
    df.setTimeZone(TimeZones.getCurrent());
    return df.format(date);
}
Example 79
Project: ApprovalTests.Java-master  File: ChangeDateVariableSetter.java View source code
/***********************************************************************/
public void setFor(DatabaseObject forObject, int atStage, Statement stmt) throws SQLException {
    if (atStage == AutomaticVariableSetter.UPDATE) {
        ((ChangeDateAware) forObject).setChangeDate(new Timestamp(System.currentTimeMillis()));
    } else if (atStage == AutomaticVariableSetter.INSERT) {
        if (forObject instanceof AddDateAware && ((AddDateAware) forObject).getAddDate() != null) {
            ((ChangeDateAware) forObject).setChangeDate(((AddDateAware) forObject).getAddDate());
        } else {
            ((ChangeDateAware) forObject).setChangeDate(new Timestamp(System.currentTimeMillis()));
        }
    }
}
Example 80
Project: avaje-ebeanorm-examples-master  File: CustomerTest.java View source code
@Test
public void canInsert() {
    Customer customer = new Customer();
    customer.setName("Rob");
    //customer.setFoo("one");
    customer.save();
//
//    assertThat(customer.getId()).isNotNull();
//    Customer rob = Ebean.find(Customer.class)
//        .where().eq("name", "Rob")
//        .findUnique();
//
//    rob.setShortDesc("cone");
//    Ebean.save(rob);
//    long now = System.currentTimeMillis();
//    Timestamp ts = new Timestamp(now - 1000*60*10);
//
//    List<Customer> list = Ebean.find(Customer.class)
//        .asOf(ts)
//        .findList();
//
//    System.out.print("asd");
}
Example 81
Project: avaje-ebeanorm-master  File: CustomerTest.java View source code
@Test
public void canInsert() {
    Customer customer = new Customer();
    customer.setName("Rob");
    //customer.setFoo("one");
    customer.save();
//
//    assertThat(customer.getId()).isNotNull();
//    Customer rob = Ebean.find(Customer.class)
//        .where().eq("name", "Rob")
//        .findUnique();
//
//    rob.setShortDesc("cone");
//    Ebean.save(rob);
//    long now = System.currentTimeMillis();
//    Timestamp ts = new Timestamp(now - 1000*60*10);
//
//    List<Customer> list = Ebean.find(Customer.class)
//        .asOf(ts)
//        .findList();
//
//    System.out.print("asd");
}
Example 82
Project: beanfuse-master  File: OnlineActivityServiceImpl.java View source code
public void save(OnlineActivity info) {
    SessionActivity record = (SessionActivity) Model.newInstance(SessionActivity.class);
    record.setSessionid(info.getSessionid());
    record.setName((String) info.getPrincipal());
    record.setFullname(info.getFullname());
    record.setCategory(info.getCategory());
    record.setLoginAt(info.getLoginAt());
    record.setHost(info.getHost());
    record.setLastAccessAt(info.getLastAccessAt());
    record.setLogoutAt(new Timestamp(System.currentTimeMillis()));
    record.setRemark(info.getRemark());
    record.calcOnlineTime();
    entityDao.saveOrUpdate(record);
}
Example 83
Project: cambodia-master  File: test.java View source code
public static void main(String[] args) {
    long cc = System.currentTimeMillis();
    Timestamp a = new Timestamp(cc);
    System.out.println(cc);
    System.out.println(a.getTime());
    java.util.Date b = (java.util.Date) a;
    System.out.println(b.getTime());
//	  LoggerHelper.error(test.class, "ÄãºÃ");
//	  CASchePara casp=new CASchePara();
//	  casp.setDstTable("j_ca_command_out");
//	  casp.setDstTableBak("j_ca_command_out_bak");
//	  CADB db=new CADB("jdbc:oracle:thin:@192.168.1.203:1521:boss","busi","busi");
//	  Thread move=new Thread(new MoveCaOutToBak(casp,db));
//	  move.start();
}
Example 84
Project: citrus-tool-master  File: SqlTimestampConverter.java View source code
public Object convert(Object value, ConvertChain chain) {
    if (value == null) {
        throw new ConvertFailedException().setDefaultValue(DEFAULT_VALUE);
    }
    if (value instanceof Timestamp) {
        return value;
    }
    if (value instanceof String) {
        String strValue = ((String) value).trim();
        try {
            return Timestamp.valueOf(strValue);
        } catch (IllegalArgumentException e) {
            if (strValue.length() > 0) {
                throw new ConvertFailedException(e);
            }
            throw new ConvertFailedException().setDefaultValue(DEFAULT_VALUE);
        }
    }
    return chain.convert(value);
}
Example 85
Project: ebean-master  File: TestMarkAsDirty.java View source code
@Test
public void test() throws InterruptedException {
    EBasicVer bean = new EBasicVer("markAsDirty");
    Ebean.save(bean);
    Timestamp lastUpdate = bean.getLastUpdate();
    Assert.assertNotNull(lastUpdate);
    Thread.sleep(100);
    // ensure the update occurs and version property is updated/incremented
    Ebean.markAsDirty(bean);
    Ebean.save(bean);
    Timestamp lastUpdate2 = bean.getLastUpdate();
    Assert.assertNotNull(lastUpdate2);
    Assert.assertNotEquals(lastUpdate, lastUpdate2);
}
Example 86
Project: editor-de-servicos-master  File: LocalDateTimeAttributeConverterTest.java View source code
@Test
public void deveConverterTimestampEmLocalDateTime() {
    LocalDateTimeAttributeConverter converter = new LocalDateTimeAttributeConverter();
    LocalDateTime expectedLocalDateTime = LocalDateTime.now();
    Timestamp timestamp = Timestamp.from(expectedLocalDateTime.toInstant(ZoneOffset.UTC));
    LocalDateTime actualLocalDateTime = converter.convertToEntityAttribute(timestamp);
    assertThat(actualLocalDateTime, equalTo(expectedLocalDateTime));
}
Example 87
Project: eql-master  File: ReplaceTest.java View source code
@Test
public void test1() {
    new Eql().id("dropTestTable").execute();
    new Eql().id("createTestTable").params(new Timestamp(1383122146000l)).execute();
    String str = new Eql().selectFirst("replace1").params("x").dynamics("DUAL").execute();
    assertThat(str, is("x"));
    str = new Eql().selectFirst("replace2").params("x").dynamics(ImmutableMap.of("table", "DUAL")).execute();
    assertThat(str, is("x"));
}
Example 88
Project: evosuite-master  File: DateConverterTest2.java View source code
/**
     * Convert a Date or Calendar objects to the time in millisconds
     * @param date The date or calendar object
     * @return The time in milliseconds
     */
long getTimeInMillis(Object date) {
    if (date instanceof java.sql.Timestamp) {
        // ---------------------- JDK 1.3 Fix ----------------------
        // N.B. Prior to JDK 1.4 the Timestamp's getTime() method
        //      didn't include the milliseconds. The following code
        //      ensures it works consistently accross JDK versions
        java.sql.Timestamp timestamp = (java.sql.Timestamp) date;
        long timeInMillis = ((timestamp.getTime() / 1000) * 1000);
        timeInMillis += timestamp.getNanos() / 1000000;
        return timeInMillis;
    }
    if (date instanceof Calendar) {
        return ((Calendar) date).getTime().getTime();
    } else {
        return ((Date) date).getTime();
    }
}
Example 89
Project: ExcelTool-master  File: TestExtend.java View source code
@Test
public void test() throws WriteException, FileNotFoundException {
    ExtendUtil extendUtil = new ExtendUtil();
    List<TestBean> beanList = new ArrayList<TestBean>();
    for (int i = 0; i < 3000; i++) {
        TestBean bean = new TestBean();
        bean.setIntTest(10000000);
        bean.setStrTest("努力造轮�");
        bean.setTimeTest(new Timestamp(System.currentTimeMillis()));
        beanList.add(bean);
    }
    OutputStream out = new FileOutputStream("d:/yy-export-excel/test3.xls");
    extendUtil.exportByAnnotation(out, beanList);
}
Example 90
Project: extreme-fishbowl-master  File: SqlTimestampConverterTestCase.java View source code
/**
     * Test default String to java.sql.Timestamp conversion
     */
public void testDefaultStringToTypeConvert() {
    // Create & Configure the Converter
    DateTimeConverter converter = makeConverter();
    converter.setUseLocaleFormat(false);
    // Valid String --> java.sql.Timestamp Conversion
    String testString = "2006-10-23 15:36:01.0";
    Object expected = toType(testString, "yyyy-MM-dd HH:mm:ss.S", null);
    validConversion(converter, expected, testString);
    // Invalid String --> java.sql.Timestamp Conversion
    invalidConversion(converter, "2006/09/21 15:36:01.0");
    invalidConversion(converter, "2006-10-22");
    invalidConversion(converter, "15:36:01");
}
Example 91
Project: fastcatsearch-master  File: JobSchedulerTest.java View source code
public void test1() throws SettingException, FastcatSearchException {
    JobService c = JobService.getInstance();
    c.start();
    //		c.setSchedule("addJob","org.fastcatsearch.ir.job.AddJob", "8 5", Timestamp.valueOf("2010-10-08 11:42"), 6000, true);
    try {
        Thread.sleep(1000 * 60);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Example 92
Project: foodtrucklocator-master  File: BDFoodTruck.java View source code
public static List<FoodTruck> select(String dateDebut, String dateFin) {
    List<FoodTruck> list = new ArrayList<>();
    PreparedStatement ps = null;
    Connection conn = connect();
    dateFin += ENDTIME + TIMEZONE;
    try {
        ps = conn.prepareStatement(SELECT_DATE);
        ps.setTimestamp(1, new java.sql.Timestamp(ConvertisseurDate.stringDate(dateDebut).getTime()));
        ps.setTimestamp(2, new java.sql.Timestamp(ConvertisseurDate.stringTimestamp(dateFin).getTime()));
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            list.add(new FoodTruck(rs.getString("truckid"), rs.getString("camion"), rs.getString("lieu"), rs.getFloat("longitude"), rs.getFloat("latitude"), rs.getTimestamp("heure_debut"), rs.getTimestamp("heure_fin")));
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } finally {
        CloseConnection(ps);
    }
    diconnect(conn);
    return list;
}
Example 93
Project: Grendel-Scan-master  File: DateDecoder.java View source code
@Override
public Object decodeObject(Object shell, Object encodedObject, Class desiredClass) {
    java.util.Date result = null;
    if (java.sql.Date.class.isAssignableFrom(desiredClass)) {
        if (encodedObject instanceof java.util.Date) {
            java.util.Date date = (java.util.Date) encodedObject;
            result = new java.sql.Date(date.getTime());
        } else if (encodedObject instanceof Calendar) {
            Calendar calendar = (Calendar) encodedObject;
            result = new java.sql.Date(calendar.getTimeInMillis());
        } else if (encodedObject instanceof Number) {
            Number number = (Number) encodedObject;
            result = new java.sql.Date(number.longValue());
        }
    } else if (java.sql.Timestamp.class.isAssignableFrom(desiredClass)) {
        if (encodedObject instanceof java.util.Date) {
            java.util.Date date = (java.util.Date) encodedObject;
            result = new java.sql.Timestamp(date.getTime());
        } else if (encodedObject instanceof Calendar) {
            Calendar calendar = (Calendar) encodedObject;
            result = new java.sql.Timestamp(calendar.getTimeInMillis());
        } else if (encodedObject instanceof Number) {
            Number number = (Number) encodedObject;
            result = new java.sql.Timestamp(number.longValue());
        }
    } else if (java.sql.Time.class.isAssignableFrom(desiredClass)) {
        if (encodedObject instanceof java.util.Date) {
            java.util.Date date = (java.util.Date) encodedObject;
            result = new java.sql.Time(date.getTime());
        } else if (encodedObject instanceof Calendar) {
            Calendar calendar = (Calendar) encodedObject;
            result = new java.sql.Time(calendar.getTimeInMillis());
        } else if (encodedObject instanceof Number) {
            Number number = (Number) encodedObject;
            result = new java.sql.Time(number.longValue());
        }
    } else if (java.util.Date.class.isAssignableFrom(desiredClass)) {
        if (encodedObject instanceof java.util.Date) {
            result = (java.util.Date) encodedObject;
        } else if (encodedObject instanceof Calendar) {
            Calendar calendar = (Calendar) encodedObject;
            result = calendar.getTime();
        } else if (encodedObject instanceof Number) {
            Number number = (Number) encodedObject;
            result = new java.util.Date(number.longValue());
        }
    }
    if (result == null) {
        DecoderFactory.invalidType(encodedObject, desiredClass);
    }
    return result;
}
Example 94
Project: Hive-Cassandra-master  File: CassandraLazyTimestamp.java View source code
@Override
public void init(ByteArrayRef bytes, int start, int length) {
    if (length == 8) {
        try {
            ByteBuffer buf = ByteBuffer.wrap(bytes.getData(), start, length);
            data.set(new Timestamp(buf.getLong(buf.position())));
            isNull = false;
            return;
        } catch (Throwable ie) {
        }
    }
    super.init(bytes, start, length);
}
Example 95
Project: hprose-java-master  File: TimestampSerializer.java View source code
@Override
public final void serialize(Writer writer, Timestamp time) throws IOException {
    super.serialize(writer, time);
    OutputStream stream = writer.stream;
    Calendar calendar = DateTime.toCalendar(time);
    ValueWriter.writeDateOfCalendar(stream, calendar);
    ValueWriter.writeTimeOfCalendar(stream, calendar, false, true);
    ValueWriter.writeNano(stream, time.getNanos());
    stream.write(TagSemicolon);
}
Example 96
Project: infoobject-plugin-master  File: XsltMetadataExtractorTest.java View source code
public void testHtml() throws IOException, TransformerConfigurationException {
    XsltMetadataExtractor xslExtractor = new XsltMetadataExtractor();
    xslExtractor.addXslt("classpath:org/infoobject/xslt/html.xsl");
    // xslExtractor.addXslt("classpath:org/infoobject/xslt/mediawiki.xsl");
    final MetadataExtractorResult res = xslExtractor.extract("http://www.spiegel.de");
    final Metadata metadata = new Metadata(res.getMetadataGraph(), new Timestamp(System.currentTimeMillis()));
    System.out.printf("depiction: " + metadata.getDepiction());
}
Example 97
Project: InSpider-master  File: ToDateTimeTransform.java View source code
@Execute
public Timestamp execute(@Input("value") final String value) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    final Matcher matcher;
    if ((matcher = datePattern.matcher(value)).matches()) {
        final String date = matcher.group(1);
        final String time = matcher.group(2);
        return Timestamp.valueOf(date + " " + time);
    }
    return null;
}
Example 98
Project: javasec-master  File: RmDataBinding.java View source code
public void initBinder(WebDataBinder binder, WebRequest request) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, true));
    binder.registerCustomEditor(java.sql.Date.class, new org.quickbundle.third.spring.web.bind.CustomSqlDateEditor(dateFormat, true));
    SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    datetimeFormat.setLenient(false);
    binder.registerCustomEditor(java.sql.Timestamp.class, new CustomTimestampEditor(datetimeFormat, true));
}
Example 99
Project: lutece-core-master  File: UserLogDAO.java View source code
/**
     * Calculate the number of connections with a given ip_address by a determinate time
     * 
     * @param userLog
     *            The Log of connection
     * @param nIntervalMinutes
     *            The number of minutes since the last connection
     * @return int
     */
public int selectLoginErrors(UserLog userLog, int nIntervalMinutes) {
    int nCount = 0;
    java.sql.Timestamp dateEnd = new java.sql.Timestamp(new java.util.Date().getTime());
    java.sql.Timestamp dateBegin = new java.sql.Timestamp(dateEnd.getTime() - (nIntervalMinutes * 1000L * 60L));
    DAOUtil daoUtil = new DAOUtil(SQL_QUERY_SELECT_LOGIN_ERRORS);
    daoUtil.setString(1, userLog.getIpAddress());
    daoUtil.setTimestamp(2, dateBegin);
    daoUtil.setTimestamp(3, dateEnd);
    daoUtil.executeQuery();
    if (daoUtil.next()) {
        nCount = daoUtil.getInt(1);
    }
    daoUtil.free();
    return nCount;
}
Example 100
Project: qb-core-master  File: RmDataBinding.java View source code
public void initBinder(WebDataBinder binder, WebRequest request) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, true));
    binder.registerCustomEditor(java.sql.Date.class, new org.quickbundle.third.spring.web.bind.CustomSqlDateEditor(dateFormat, true));
    SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    datetimeFormat.setLenient(false);
    binder.registerCustomEditor(java.sql.Timestamp.class, new CustomTimestampEditor(datetimeFormat, true));
}
Example 101
Project: spring4-sandbox-master  File: JdbcTemplateConferenceDaoImpl.java View source code
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
    PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] { "id" });
    ps.setString(1, conference.getName());
    ps.setString(2, conference.getSlug());
    ps.setString(3, conference.getDescription());
    ps.setTimestamp(4, new java.sql.Timestamp(conference.getStartedDate().getTime()));
    ps.setTimestamp(5, new java.sql.Timestamp(conference.getEndedDate().getTime()));
    return ps;
}