Example usage for java.sql Timestamp valueOf

List of usage examples for java.sql Timestamp valueOf

Introduction

In this page you can find the example usage for java.sql Timestamp valueOf.

Prototype

@SuppressWarnings("deprecation")
public static Timestamp valueOf(LocalDateTime dateTime) 

Source Link

Document

Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .

Usage

From source file:cn.mljia.common.notify.utils.DateUtils.java

public static Timestamp strToTimestamp(Date date) {
    return Timestamp.valueOf(formatTimestamp.format(date));
}

From source file:cn.mljia.common.notify.utils.DateUtils.java

public static Timestamp getCurTimestamp() {
    return Timestamp.valueOf(formatTimestamp.format(new Date()));
}

From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java

public String getAndUpdateLastCartridgeStatsHourlyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {/*from  ww  w.j ava2 s . co m*/
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM CARTRIDGE_STATS_LAST_HOURLY_TS WHERE ID='LatestTS'";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            lastSummaryTs = resultSet.getTimestamp("TIMESTMP");
        } else {
            lastSummaryTs = new Timestamp(0);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO CARTRIDGE_STATS_LAST_HOURLY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?";
        PreparedStatement ps1 = connection.prepareStatement(currentSql);
        ps1.setTimestamp(1, currentTs);
        ps1.setTimestamp(2, currentTs);
        ps1.execute();

    } catch (SQLException e) {
        log.error(
                "Error occurred while trying to get and update the last hourly timestamp for cartridge stats. ",
                e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}

From source file:com.hihframework.core.utils.DateUtils.java

/**
 * 23.59.59.999? param:2004-08-20,return:2004-08-31
 * 23.59.59.999//from w  ww  . jav a  2s .  c  o  m
 *
 * @param date
 * @return
 */
public static Timestamp getMaxDayInMonth(java.sql.Date date) {

    Calendar cale = Calendar.getInstance();
    cale.setTime(date);
    cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
    java.sql.Date newDate = new java.sql.Date(cale.getTimeInMillis());

    cale = null;
    return Timestamp.valueOf(newDate.toString() + " 23:59:59.999");
}

From source file:org.apache.hawq.pxf.plugins.hive.HiveResolver.java

int initPartitionFields(StringBuilder parts) {
    if (partitionKeys.equals(HiveDataFragmenter.HIVE_NO_PART_TBL)) {
        return 0;
    }/*from w w  w .  j a  va 2  s  .c  o m*/
    String[] partitionLevels = partitionKeys.split(HiveDataFragmenter.HIVE_PARTITIONS_DELIM);
    for (String partLevel : partitionLevels) {
        String[] levelKey = partLevel.split(HiveDataFragmenter.HIVE_1_PART_DELIM);
        String type = levelKey[1];
        String val = levelKey[2];
        parts.append(delimiter);

        if (isDefaultPartition(type, val)) {
            parts.append(nullChar);
        } else {
            // ignore the type's parameters
            String typeName = type.replaceAll("\\(.*\\)", "");
            switch (typeName) {
            case serdeConstants.STRING_TYPE_NAME:
            case serdeConstants.VARCHAR_TYPE_NAME:
            case serdeConstants.CHAR_TYPE_NAME:
                parts.append(val);
                break;
            case serdeConstants.BOOLEAN_TYPE_NAME:
                parts.append(Boolean.parseBoolean(val));
                break;
            case serdeConstants.TINYINT_TYPE_NAME:
            case serdeConstants.SMALLINT_TYPE_NAME:
                parts.append(Short.parseShort(val));
                break;
            case serdeConstants.INT_TYPE_NAME:
                parts.append(Integer.parseInt(val));
                break;
            case serdeConstants.BIGINT_TYPE_NAME:
                parts.append(Long.parseLong(val));
                break;
            case serdeConstants.FLOAT_TYPE_NAME:
                parts.append(Float.parseFloat(val));
                break;
            case serdeConstants.DOUBLE_TYPE_NAME:
                parts.append(Double.parseDouble(val));
                break;
            case serdeConstants.TIMESTAMP_TYPE_NAME:
                parts.append(Timestamp.valueOf(val));
                break;
            case serdeConstants.DATE_TYPE_NAME:
                parts.append(Date.valueOf(val));
                break;
            case serdeConstants.DECIMAL_TYPE_NAME:
                parts.append(HiveDecimal.create(val).bigDecimalValue());
                break;
            case serdeConstants.BINARY_TYPE_NAME:
                Utilities.byteArrayToOctalString(val.getBytes(), parts);
                break;
            default:
                throw new UnsupportedTypeException("Unsupported partition type: " + type);
            }
        }
    }
    return partitionLevels.length;
}

From source file:net.niyonkuru.koodroid.ui.UsageFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    int id = loader.getId();

    switch (id) {
    case AIRTIME_TOKEN: {
        String used = null;//from  w w w.j av  a  2 s.co m
        String included = null;
        String chargeable = null;
        String remaining = null;
        Object timestamp = null;

        if (data.moveToFirst()) {
            used = data.getString(AirtimesQuery.USED);
            included = data.getString(AirtimesQuery.INCLUDED);
            chargeable = data.getString(AirtimesQuery.CHARGEABLE);
            remaining = data.getString(AirtimesQuery.REMAINING);
            timestamp = Timestamp.valueOf(data.getString(AirtimesQuery.UPDATED));
        }
        mAirtimeUsed.setText(used);
        mAirtimeIncluded.setText(included);
        mAirtimeChargeable.setText(chargeable);
        mAirtimeRemaining.setText(remaining);
        mAirtimeUpdateTime.setTag(timestamp);
        break;
    }
    case TEXT_TOKEN: {
        data.moveToFirst();

        mTextUsed.setText(data.getString(UsagesQuery.COUNT));

        mTextCharged.setText(formatMoney(data.getString(UsagesQuery.AMOUNT)));

        saveUsageTimestamps(data);
        break;
    }
    case DATA_TOKEN: {
        data.moveToFirst();

        mDataUsed.setText(UsageUtils.format(mContext, data.getDouble(UsagesQuery.COUNT), getNumberFormat()));

        mDataCharged.setText(formatMoney(data.getString(UsagesQuery.AMOUNT)));

        saveUsageTimestamps(data);
        break;
    }
    }

    updateTimestamps();
}

From source file:com.hp.rest.OrdersHandle.java

@POST
@Path("/putStaffJourney")
@Consumes(MediaType.APPLICATION_JSON)/*from  w  w  w  .  ja  v  a2  s  .  com*/
public Response putStaffJourney(String pData) throws UnsupportedEncodingException {
    //        ByteArrayInputStream pDataIS = null;
    //        try {
    //               pDataIS = new ByteArrayInputStream(pData.getBytes("UTF-8"));
    //               System.out.println(pDataIS.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Logger.getLogger(OrdersHandle.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    // pair to object
    ObjectMapper mapper = new ObjectMapper();
    RoadManagement roadManagement = new RoadManagement();
    try {
        //         File jsonFile = new File(jsonFilePath);
        roadManagement = mapper.readValue(pData, RoadManagement.class);
        //System.out.println(track.getmMaKhachHang());
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    String address = "";
    if (roadManagement != null) {
        roadManagement.setThoiGian(Timestamp.valueOf(dateFormat.format(date)));

        // Set address
        //            address = Utility.getAddress(roadManagement.getViDo(), roadManagement.getKinhDo());
        //            roadManagement.setGhiChu(address);
    }

    RoadManagementDAO roadManagementDAO = new RoadManagementDAOImpl();
    boolean status = roadManagementDAO.saveOrUpdate(roadManagement);

    JSONObject json = new JSONObject();
    try {
        json.put("status", status);
        json.put("address", address);
    } catch (JSONException ex) {
        Logger.getLogger(OrdersHandle.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Response.status(200).entity(json.toString()).build();

}

From source file:org.jumpmind.db.model.Column.java

/**
 * Tries to parse the default value of the column and returns it as an
 * object of the corresponding java type. If the value could not be parsed,
 * then the original definition is returned.
 * //from ww w  .j a  v a 2 s .  c  om
 * @return The parsed default value
 */
public Object getParsedDefaultValue() {
    if ((defaultValue != null) && (defaultValue.length() > 0)) {
        try {
            switch (mappedTypeCode) {
            case Types.TINYINT:
            case Types.SMALLINT:
                return new Short(defaultValue);
            case Types.INTEGER:
                try {
                    return new Integer(defaultValue);
                } catch (NumberFormatException e) {
                    return new Long(defaultValue);
                }
            case Types.BIGINT:
                return new Long(defaultValue);
            case Types.DECIMAL:
            case Types.NUMERIC:
                return new BigDecimal(defaultValue);
            case Types.REAL:
                return new Float(defaultValue);
            case Types.DOUBLE:
            case Types.FLOAT:
                return new Double(defaultValue);
            case Types.DATE:
                return Date.valueOf(defaultValue);
            case Types.TIME:
                return Time.valueOf(defaultValue);
            case Types.TIMESTAMP:
                return Timestamp.valueOf(defaultValue);
            case Types.BIT:
                return FormatUtils.toBoolean(defaultValue);
            default:
                if (PlatformUtils.supportsJava14JdbcTypes()
                        && (mappedTypeCode == PlatformUtils.determineBooleanTypeCode())) {
                    return FormatUtils.toBoolean(defaultValue);
                }
                break;
            }
        } catch (NumberFormatException ex) {
            return null;
        } catch (IllegalArgumentException ex) {
            return null;
        }
    }
    return defaultValue;
}

From source file:com.trackplus.ddl.DataWriter.java

private static void insertClobData(Connection con, String line) throws DDLException {
    /*//  w w w .  j a  va 2s.  c o m
    "OBJECTID",//Integer not null
    "EXCHANGEDIRECTION",//Integer not null
    "ENTITYID",//Integer not null
    "ENTITYTYPE",//Integer not null
    "FILENAME",//Varchar(255)
    "CHANGEDBY",//Integer
    "LASTEDIT",//Timestamp
    "TPUUID",//Varchar(36)
    "FILECONTENT"//Blob sub_type 1
     */

    String sql = "INSERT INTO TMSPROJECTEXCHANGE(OBJECTID, EXCHANGEDIRECTION, ENTITYID,ENTITYTYPE,FILENAME,CHANGEDBY,LASTEDIT,TPUUID,FILECONTENT) "
            + "VALUES(?,?,?,?,?,?,?,?,?)";
    StringTokenizer st = new StringTokenizer(line, ",");
    Integer objectID = Integer.valueOf(st.nextToken());
    Integer exchangeDirection = Integer.valueOf(st.nextToken());
    Integer entityID = Integer.valueOf(st.nextToken());
    Integer entityType = Integer.valueOf(st.nextToken());
    String fileName = st.nextToken();
    if ("null".equalsIgnoreCase(fileName)) {
        fileName = null;
    }
    Integer changedBy = null;
    try {
        changedBy = Integer.valueOf(st.nextToken());
    } catch (Exception ex) {
        LOGGER.debug(ex);
    }

    Timestamp lastEdit = null;
    String lastEditStr = st.nextToken();
    if (lastEditStr != null) {
        try {
            lastEdit = Timestamp.valueOf(lastEditStr);
        } catch (Exception ex) {
            LOGGER.debug(ex);
        }
    }
    String tpuid = st.nextToken();
    String base64Str = st.nextToken();
    if (base64Str.length() == 1 && " ".equals(base64Str)) {
        base64Str = "";
    }
    byte[] bytes = Base64.decodeBase64(base64Str);
    String fileContent = new String(bytes);

    try {
        PreparedStatement preparedStatement = con.prepareStatement(sql);

        preparedStatement.setInt(1, objectID);
        preparedStatement.setInt(2, exchangeDirection);
        preparedStatement.setInt(3, entityID);
        preparedStatement.setInt(4, entityType);
        preparedStatement.setString(5, fileName);
        preparedStatement.setInt(6, changedBy);
        preparedStatement.setTimestamp(7, lastEdit);
        preparedStatement.setString(8, tpuid);
        preparedStatement.setString(9, fileContent);

        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }

}

From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java

public String getAndUpdateLastCartridgeStatsDailyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {/* w ww  . j  a v a  2s.co  m*/
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM CARTRIDGE_STATS_LAST_DAILY_TS WHERE ID='LatestTS'";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            lastSummaryTs = resultSet.getTimestamp("TIMESTMP");
        } else {
            lastSummaryTs = new Timestamp(0);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO CARTRIDGE_STATS_LAST_DAILY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?";
        PreparedStatement ps1 = connection.prepareStatement(currentSql);
        ps1.setTimestamp(1, currentTs);
        ps1.setTimestamp(2, currentTs);
        ps1.execute();

    } catch (SQLException e) {
        log.error(
                "Error occurred while trying to get and update the last daily timestamp for cartridge stats. ",
                e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}