Example usage for java.sql Timestamp setNanos

List of usage examples for java.sql Timestamp setNanos

Introduction

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

Prototype

public void setNanos(int n) 

Source Link

Document

Sets this Timestamp object's nanos field to the given value.

Usage

From source file:Main.java

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    Date d = new Date(time);
    Timestamp t = new Timestamp(time);
    t.setNanos(123456789);
    System.out.println(d);//from   w  w w. j av a  2  s . c  om
    System.out.println(t);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.'");
    NumberFormat nf = new DecimalFormat("000000000");
    System.out.println(df.format(t.getTime()) + nf.format(t.getNanos()));
}

From source file:Main.java

public static void main(String[] args) {
    java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2013-04-06 09:01:10");

    long tsTime2 = ts2.getTime();

    System.out.println(tsTime2);/*  ww  w.j  a  va  2s.  co m*/

    ts2.setNanos(123);

    System.out.println(tsTime2);
}

From source file:Main.java

public static Timestamp getCurrentDate() {

    Calendar c = Calendar.getInstance();
    c.set(c.get(1), c.get(2), c.get(5), 0, 0, 0);
    Timestamp t = new Timestamp(c.getTime().getTime());
    t.setNanos(0);
    return t;/*w ww  .  j av a2 s .c o m*/
}

From source file:com.concursive.connect.web.modules.calendar.utils.CalendarViewUtils.java

public static CalendarView generateCalendarView(Connection db, CalendarBean calendarInfo, Project project,
        User user, String filter) throws SQLException {

    // Generate a new calendar
    CalendarView calendarView = new CalendarView(calendarInfo, user.getLocale());

    if (calendarInfo.getShowHolidays()) {
        // Add some holidays based on the user locale
        calendarView.addHolidays();//from  w w w .j a v  a 2  s . c o  m
    }

    // Set Start and End Dates for the view, use the user's timezone offset
    // (always use Locale.US which matches the URL format)
    String startValue = calendarView.getCalendarStartDate(calendarInfo.getSource());
    LOG.debug(startValue);
    String userStartValue = DateUtils.getUserToServerDateTimeString(calendarInfo.getTimeZone(),
            DateFormat.SHORT, DateFormat.LONG, startValue, Locale.US);
    LOG.debug(userStartValue);
    Timestamp startDate = DatabaseUtils.parseTimestamp(userStartValue);
    startDate.setNanos(0);
    LOG.debug(startDate);

    Timestamp endDate = DatabaseUtils.parseTimestamp(
            DateUtils.getUserToServerDateTimeString(calendarInfo.getTimeZone(), DateFormat.SHORT,
                    DateFormat.LONG, calendarView.getCalendarEndDate(calendarInfo.getSource()), Locale.US));
    endDate.setNanos(0);

    if (ProjectUtils.hasAccess(project.getId(), user, "project-tickets-view")) {
        // Show open and closed tickets
        TicketList ticketList = new TicketList();
        ticketList.setProjectId(project.getId());
        ticketList.setOnlyAssigned(true);
        ticketList.setAlertRangeStart(startDate);
        ticketList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            ticketList.setOnlyOpen(true);
        } else if ("completed".equals(filter)) {
            ticketList.setOnlyClosed(true);
        }

        // Retrieve the tickets that meet the criteria
        ticketList.buildList(db);
        for (Ticket thisTicket : ticketList) {
            if (thisTicket.getEstimatedResolutionDate() != null) {
                String alertDate = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisTicket.getEstimatedResolutionDate());
                calendarView.addEvent(alertDate, CalendarEventList.EVENT_TYPES[11], thisTicket);
            }
        }

        // Retrieve the dates in which a ticket has been resolved
        HashMap<String, Integer> dayEvents = ticketList.queryRecordCount(db, UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.TICKET],
                    dayEvents.get(thisDay));
        }
    }
    if (ProjectUtils.hasAccess(project.getId(), user, "project-plan-view")) {
        // List open and closed Requirements
        RequirementList requirementList = new RequirementList();
        requirementList.setProjectId(project.getId());
        requirementList.setBuildAssignments(false);
        requirementList.setAlertRangeStart(startDate);
        requirementList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            requirementList.setOpenOnly(true);
        } else if ("completed".equals(filter)) {
            requirementList.setClosedOnly(true);
        }

        // Retrieve the requirements that meet the criteria
        requirementList.buildList(db);
        // @todo fix timezone for query counts
        requirementList.buildPlanActivityCounts(db);
        for (Requirement thisRequirement : requirementList) {
            // Display Milestone startDate
            if (thisRequirement.getStartDate() != null) {
                String start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisRequirement.getStartDate());
                calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[16], thisRequirement);
            }
            // Display Milestone endDate
            if (thisRequirement.getDeadline() != null) {
                String end = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisRequirement.getDeadline());
                calendarView.addEvent(end, CalendarEventList.EVENT_TYPES[17], thisRequirement);
            }
        }

        // Retrieve the dates in which a requirement has a start or end date
        HashMap<String, HashMap<String, Integer>> dayGroups = requirementList.queryRecordCount(db,
                UserUtils.getUserTimeZone(user));
        for (String type : dayGroups.keySet()) {
            if ("startdate".equals(type)) {
                HashMap<String, Integer> dayEvents = dayGroups.get(type);
                for (String thisDay : dayEvents.keySet()) {
                    calendarView.addEventCount(thisDay,
                            CalendarEventList.EVENT_TYPES[CalendarEventList.MILESTONE_START],
                            dayEvents.get(thisDay));
                }
            } else if ("enddate".equals(type)) {
                HashMap<String, Integer> dayEvents = dayGroups.get(type);
                for (String thisDay : dayEvents.keySet()) {
                    calendarView.addEventCount(thisDay,
                            CalendarEventList.EVENT_TYPES[CalendarEventList.MILESTONE_END],
                            dayEvents.get(thisDay));
                }
            }

        }

        // Retrieve assignments that meet the criteria
        AssignmentList assignmentList = new AssignmentList();
        assignmentList.setProjectId(project.getId());
        assignmentList.setOnlyIfRequirementOpen(true);
        assignmentList.setAlertRangeStart(startDate);
        assignmentList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            assignmentList.setIncompleteOnly(true);
        } else if ("completed".equals(filter)) {
            assignmentList.setClosedOnly(true);
        }

        // Display the user's assignments by due date
        assignmentList.buildList(db);
        for (Assignment thisAssignment : assignmentList) {
            if (thisAssignment.getDueDate() != null) {
                String dueDate = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisAssignment.getDueDate());
                calendarView.addEvent(dueDate, CalendarEventList.EVENT_TYPES[8], thisAssignment);
            }
        }

        // Retrieve the dates in which an assignment has a due date
        HashMap<String, Integer> dayEvents = assignmentList.queryAssignmentRecordCount(db,
                UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.ASSIGNMENT],
                    dayEvents.get(thisDay));
        }
    }

    if (ProjectUtils.hasAccess(project.getId(), user, "project-calendar-view")) {
        MeetingList meetingList = new MeetingList();
        meetingList.setProjectId(project.getId());
        meetingList.setEventSpanStart(startDate);
        if (!calendarInfo.isAgendaView()) {
            // limit the events to the date range chosen
            meetingList.setEventSpanEnd(endDate);
        }
        meetingList.setBuildAttendees(true);
        meetingList.buildList(db);
        LOG.debug("Meeting count = " + meetingList.size());
        // Display the meetings by date
        for (Meeting thisMeeting : meetingList) {
            if (thisMeeting.getStartDate() != null) {
                String start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisMeeting.getStartDate());
                if ("pending".equals(filter)) {
                    if (thisMeeting.getStartDate().getTime() > System.currentTimeMillis()) {
                        calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                                thisMeeting);
                    }
                } else if ("completed".equals(filter)) {
                    if (thisMeeting.getEndDate().getTime() < System.currentTimeMillis()) {
                        calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                                thisMeeting);
                    }
                } else {
                    if (calendarInfo.isAgendaView()) {
                        // Display meetings that started before today, but last greater than today, on the startDate of the calendar display
                        if (thisMeeting.getStartDate().before(startDate)) {
                            start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                                    DateFormat.SHORT, startDate);
                        }
                    }
                    calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                            thisMeeting);
                }
                LOG.debug("Meeting added for date: " + start);
            }
        }

        // Retrieve the dates for meeting events
        HashMap<String, Integer> dayEvents = meetingList.queryRecordCount(db, UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            LOG.debug("addingCount: " + thisDay + " = " + dayEvents.get(thisDay));
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                    dayEvents.get(thisDay));
        }
    }
    return calendarView;
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

public static Timestamp readTimestamp(ByteBuf in) {
    byte length = in.readByte();
    int year = readInt(in);
    byte month = readByte(in);
    byte date = readByte(in);
    int hour = readByte(in);
    int minute = readByte(in);
    int second = readByte(in);
    if (length == 11) {
        long nanos = readUB4(in) * 1000;
        Calendar cal = getLocalCalendar();
        cal.set(year, --month, date, hour, minute, second);
        Timestamp time = new Timestamp(cal.getTimeInMillis());
        time.setNanos((int) nanos);
        return time;
    } else {/*  w w  w .j  a v a2s . co  m*/
        Calendar cal = getLocalCalendar();
        cal.set(year, --month, date, hour, minute, second);
        return new Timestamp(cal.getTimeInMillis());
    }
}

From source file:com.concursive.connect.web.modules.login.utils.UserUtils.java

public static Timestamp getEnteredTimestampFromGuid(String guid) {
    long longValue = Long.parseLong(guid.substring(13, guid.indexOf("-")));
    int nanos = Integer.parseInt(guid.substring(guid.indexOf("-") + 1, guid.lastIndexOf("-")));
    LOG.trace("entered value: " + longValue + "." + nanos);
    Timestamp timestamp = new Timestamp(longValue);
    timestamp.setNanos(nanos);
    return timestamp;
}

From source file:com.clustercontrol.jobmanagement.util.JobKickFilterPropertyUtil.java

/**
 * DTO?????/*from ww w.j a v a  2  s  .c  o m*/
 *
 * @param property
 * @return
 */
public static JobKickFilterInfo property2dto(Property property) {
    JobKickFilterInfo info = new JobKickFilterInfo();
    ArrayList<?> values = null;

    // ID
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.JOBKICK_ID);
    if (!"".equals(values.get(0))) {
        info.setJobkickId((String) values.get(0));
    }
    // ??
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.JOBKICK_NAME);
    if (!"".equals(values.get(0))) {
        info.setJobkickName((String) values.get(0));
    }
    // 
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.JOBKICK_TYPE);
    if (!"".equals(values.get(0))) {
        info.setJobkickType((Integer) JobKickTypeMessage.stringToType((String) values.get(0)));
    }
    // ID
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.JOBUNIT_ID);
    if (!"".equals(values.get(0))) {
        info.setJobunitId((String) values.get(0));
    }
    // ID
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.JOB_ID);
    if (!"".equals(values.get(0))) {
        info.setJobId((String) values.get(0));
    }
    // ID
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.CALENDAR_ID);
    if (!"".equals(values.get(0))) {
        info.setCalendarId((String) values.get(0));
    }
    // 
    Boolean validFlg = null;
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.VALID_FLG);
    if (!"".equals(values.get(0))) {
        if (ValidMessage.STRING_VALID.equals(values.get(0))) {
            validFlg = true;
        } else {
            validFlg = false;
        }
    }
    info.setValidFlg(validFlg);

    //??
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.REG_USER);
    if (!"".equals(values.get(0))) {
        info.setRegUser((String) values.get(0));
    }

    //?(From)
    Timestamp regFromDate = null;
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.REG_FROM_DATE);
    if (values.get(0) instanceof Date) {
        regFromDate = new Timestamp(((Date) values.get(0)).getTime());
        regFromDate.setNanos(999999999);
        info.setRegFromDate(regFromDate.getTime());
    }

    //?(To)
    Timestamp regToDate = null;
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.REG_TO_DATE);
    if (values.get(0) instanceof Date) {
        regToDate = new Timestamp(((Date) values.get(0)).getTime());
        regToDate.setNanos(999999999);
        info.setRegToDate(regToDate.getTime());
    }

    //
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.UPDATE_USER);
    if (!"".equals(values.get(0))) {
        info.setUpdateUser((String) values.get(0));
    }
    //(From)
    Timestamp updateFromDate = null;
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.UPDATE_FROM_DATE);
    if (values.get(0) instanceof Date) {
        updateFromDate = new Timestamp(((Date) values.get(0)).getTime());
        updateFromDate.setNanos(999999999);
        info.setUpdateFromDate(updateFromDate.getTime());
    }

    //(To)
    Timestamp updateToDate = null;
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.UPDATE_TO_DATE);
    if (values.get(0) instanceof Date) {
        updateToDate = new Timestamp(((Date) values.get(0)).getTime());
        updateToDate.setNanos(999999999);
        info.setUpdateToDate(updateToDate.getTime());
    }

    //ID
    values = PropertyUtil.getPropertyValue(property, JobKickFilterConstant.OWNER_ROLE_ID);
    if (!"".equals(values.get(0))) {
        info.setOwnerRoleId((String) values.get(0));
    }
    return info;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

public static Timestamp getTimestampForOffsetValue(String offsetValue) {
    final String[] parts = StringUtils.splitByWholeSeparator(offsetValue, OFFSET_VALUE_NANO_SEPARATOR);
    Utils.checkState(parts.length <= 2,
            String.format(// w  ww .  j a  va 2  s  .c om
                    "offsetValue of %s invalid; should contain at most one occurence of nanos separator %s",
                    offsetValue, OFFSET_VALUE_NANO_SEPARATOR));

    final long millis = Long.parseLong(parts[0]);
    Timestamp timestamp = new Timestamp(millis);

    if (parts.length == 2) {
        final String nanosStr = parts[1];
        if (StringUtils.isNotBlank(nanosStr) && StringUtils.isNumeric(nanosStr)) {
            final int nanos = Integer.parseInt(nanosStr) % JdbcUtil.NANOS_TO_MILLIS_ADJUSTMENT;
            // in a Timestamp, nanos also includes the millisecond portion, so we need to incorporate that
            final long nanosFromMillis = millis % 1000;
            timestamp.setNanos(((int) nanosFromMillis * JdbcUtil.NANOS_TO_MILLIS_ADJUSTMENT) + nanos);
        }
    }

    return timestamp;
}

From source file:TypeConversionHelper.java

/**
 * Converts a string in JDBC timestamp escape format to a Timestamp object.
 * To be precise, we prefer to find a JDBC escape type sequence in the format
 * "yyyy-mm-dd hh:mm:ss.fffffffff", but this does accept other separators
 * of fields, so as long as the numbers are in the order
 * year, month, day, hour, minute, second then we accept it.
 * @param s Timestamp string//from  w  ww  . j  a  v  a2 s .c o m
 * @param cal The Calendar to use for conversion
 * @return Corresponding <tt>java.sql.Timestamp</tt> value.
 * @exception java.lang.IllegalArgumentException Thrown if the format of the
 * String is invalid
 */
public static Timestamp stringToTimestamp(String s, Calendar cal) {
    int[] numbers = convertStringToIntArray(s);
    if (numbers == null || numbers.length < 6) {
        throw new IllegalArgumentException("string to time stamp" + s);
    }

    int year = numbers[0];
    int month = numbers[1];
    int day = numbers[2];
    int hour = numbers[3];
    int minute = numbers[4];
    int second = numbers[5];
    int nanos = 0;
    if (numbers.length > 6) {
        nanos = numbers[6];
    }

    Calendar thecal = cal;
    if (cal == null) {
        thecal = new GregorianCalendar();
    }
    thecal.set(Calendar.ERA, GregorianCalendar.AD);
    thecal.set(Calendar.YEAR, year);
    thecal.set(Calendar.MONTH, month - 1);
    thecal.set(Calendar.DATE, day);
    thecal.set(Calendar.HOUR_OF_DAY, hour);
    thecal.set(Calendar.MINUTE, minute);
    thecal.set(Calendar.SECOND, second);
    Timestamp ts = new Timestamp(thecal.getTime().getTime());
    ts.setNanos(nanos);

    return ts;
}

From source file:com.microsoft.sqlserver.testframework.sqlType.SqlDateTime2.java

public Object createdata() {
    Timestamp temp = new Timestamp(ThreadLocalRandom.current().nextLong(((Timestamp) minvalue).getTime(),
            ((Timestamp) maxvalue).getTime()));
    temp.setNanos(0);
    String timeNano = temp.toString().substring(0, temp.toString().length() - 1)
            + RandomStringUtils.randomNumeric(this.precision);
    // can pass string rather than converting to LocalDateTime, but leaving
    // it unchanged for now to handle prepared statements
    return LocalDateTime.parse(timeNano, formatter);
}