List of usage examples for java.sql Date Date
public Date(long date)
From source file:org.ujorm.hotels.services.DatabaseTest.java
/** Returns two Booking objects with different DateFrom attribute value */ private List<Booking> getBookings() { List<Booking> result = new ArrayList<Booking>(); Booking item1 = new Booking(); result.add(item1);/*from ww w . j a v a 2s . co m*/ item1.setDateFrom(new Date(System.currentTimeMillis() - ONE_DAY)); Booking item2 = new Booking(); result.add(item2); item2.setDateFrom(new Date(System.currentTimeMillis() + ONE_DAY)); return result; }
From source file:com.victor.fishhub.service.weatherapi.APIResponseConverterImpl.java
private Date getForecastDate(String date) { Matcher matcher = datePattern.matcher(date); if (matcher.matches()) { try {//from w w w .j a v a2 s .c om Date sqlDate = new Date(dateFormat.parse(date).getTime()); return sqlDate; } catch (ParseException ex) { ex.printStackTrace(); } } return null; }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testDateTimeTimestampWithCalendar() throws SQLException { Statement stat = conn.createStatement(); stat.execute("create table ts(x timestamp primary key)"); stat.execute("create table t(x time primary key)"); stat.execute("create table d(x date)"); Calendar utcCalendar = new GregorianCalendar(new SimpleTimeZone(0, "Z")); TimeZone old = TimeZone.getDefault(); DateTimeUtils.resetCalendar();/*from w w w. j a v a2s. co m*/ TimeZone.setDefault(TimeZone.getTimeZone("PST")); try { Timestamp ts1 = Timestamp.valueOf("2010-03-13 18:15:00"); Time t1 = new Time(ts1.getTime()); Date d1 = new Date(ts1.getTime()); // when converted to UTC, this is 03:15, which doesn't actually exist // because of summer time change at that day Timestamp ts2 = Timestamp.valueOf("2010-03-13 19:15:00"); Time t2 = new Time(ts2.getTime()); Date d2 = new Date(ts2.getTime()); PreparedStatement prep; ResultSet rs; prep = conn.prepareStatement("insert into ts values(?)"); prep.setTimestamp(1, ts1, utcCalendar); prep.execute(); prep.setTimestamp(1, ts2, utcCalendar); prep.execute(); prep = conn.prepareStatement("insert into t values(?)"); prep.setTime(1, t1, utcCalendar); prep.execute(); prep.setTime(1, t2, utcCalendar); prep.execute(); prep = conn.prepareStatement("insert into d values(?)"); prep.setDate(1, d1, utcCalendar); prep.execute(); prep.setDate(1, d2, utcCalendar); prep.execute(); rs = stat.executeQuery("select * from ts order by x"); rs.next(); assertEquals("2010-03-14 02:15:00.0", rs.getString(1)); assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp(1, utcCalendar).toString()); assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString()); assertEquals("2010-03-14 02:15:00.0", rs.getString("x")); assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp("x", utcCalendar).toString()); assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString()); rs.next(); assertEquals("2010-03-14 03:15:00.0", rs.getString(1)); assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp(1, utcCalendar).toString()); assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString()); assertEquals("2010-03-14 03:15:00.0", rs.getString("x")); assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp("x", utcCalendar).toString()); assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString()); rs = stat.executeQuery("select * from t order by x"); rs.next(); assertEquals("02:15:00", rs.getString(1)); assertEquals("18:15:00", rs.getTime(1, utcCalendar).toString()); assertEquals("02:15:00", rs.getTime(1).toString()); assertEquals("02:15:00", rs.getString("x")); assertEquals("18:15:00", rs.getTime("x", utcCalendar).toString()); assertEquals("02:15:00", rs.getTime("x").toString()); rs.next(); assertEquals("03:15:00", rs.getString(1)); assertEquals("19:15:00", rs.getTime(1, utcCalendar).toString()); assertEquals("03:15:00", rs.getTime(1).toString()); assertEquals("03:15:00", rs.getString("x")); assertEquals("19:15:00", rs.getTime("x", utcCalendar).toString()); assertEquals("03:15:00", rs.getTime("x").toString()); rs = stat.executeQuery("select * from d order by x"); rs.next(); assertEquals("2010-03-14", rs.getString(1)); assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString()); assertEquals("2010-03-14", rs.getDate(1).toString()); assertEquals("2010-03-14", rs.getString("x")); assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString()); assertEquals("2010-03-14", rs.getDate("x").toString()); rs.next(); assertEquals("2010-03-14", rs.getString(1)); assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString()); assertEquals("2010-03-14", rs.getDate(1).toString()); assertEquals("2010-03-14", rs.getString("x")); assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString()); assertEquals("2010-03-14", rs.getDate("x").toString()); } finally { TimeZone.setDefault(old); DateTimeUtils.resetCalendar(); } stat.execute("drop table ts"); stat.execute("drop table t"); stat.execute("drop table d"); }
From source file:com.taobao.adfs.database.tdhsocket.client.response.TDHSResutSet.java
public Date getDate(int columnIndex) throws SQLException { Long time = ConvertUtil.getTimeFromString(this.getString(columnIndex), null); return time == null ? null : new Date(time); }
From source file:org.apache.phoenix.util.DateUtil.java
public static Date parseDate(String dateValue) { return new Date(parseDateTime(dateValue)); }
From source file:gov.nih.nci.integration.invoker.CaTissueConsentStrategyTest.java
/** * Tests rollbackConsents using the ServiceInvocationStrategy class for the success scenario * /*from w ww. jav a2s.c o m*/ * @throws IntegrationException - IntegrationException * @throws JAXBException - JAXBException */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void rollbackConsents() throws IntegrationException, JAXBException { final Date stTime = new Date(new java.util.Date().getTime()); xsltTransformer.transform(null, null, null); EasyMock.expectLastCall().andAnswer(new IAnswer() { public Object answer() { return getRegisterConsentXMLStr(); } }).anyTimes(); final ServiceInvocationResult clientResult = new ServiceInvocationResult(); EasyMock.expect(caTissueConsentClient.rollbackConsents((String) EasyMock.anyObject())) .andReturn(clientResult); EasyMock.replay(caTissueConsentClient); final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID, getRegisterConsentXMLStr(), stTime, caTissueConsentStrategy.getStrategyIdentifier()); final ServiceInvocationResult strategyResult = caTissueConsentStrategy.rollback(serviceInvocationMessage); Assert.assertNotNull(strategyResult); }
From source file:com.intelligentz.appointmentz.controllers.addSession.java
@SuppressWarnings("Since15") @Override/*from w w w. j a v a 2 s .c om*/ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String room_id = null; String doctor_id = null; String start_time = null; String date_picked = null; ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>(); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(filePath + "temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(req); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { filePath = filePath + fileName.substring(fileName.lastIndexOf("\\")); file = new File(filePath); } else { filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1); file = new File(filePath); } fi.write(file); Files.lines(Paths.get(filePath)).forEach((line) -> { String[] cust = line.split(","); sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim()))); }); } else { if (fi.getFieldName().equals("room_id")) room_id = fi.getString(); else if (fi.getFieldName().equals("doctor_id")) doctor_id = fi.getString(); else if (fi.getFieldName().equals("start_time")) start_time = fi.getString(); else if (fi.getFieldName().equals("date_picked")) date_picked = fi.getString(); } } con = new connectToDB(); if (con.connect()) { Connection connection = con.getConnection(); Class.forName("com.mysql.jdbc.Driver"); Statement stmt = connection.createStatement(); String SQL, SQL1, SQL2; SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)"; PreparedStatement preparedStmt = connection.prepareStatement(SQL1); preparedStmt.setString(1, doctor_id); preparedStmt.setString(2, room_id); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm"); try { java.util.Date d = formatter.parse(date_picked + "-" + start_time); Date d_sql = new Date(d.getTime()); java.util.Date N = new java.util.Date(); if (N.compareTo(d) > 0) { res.sendRedirect("./error.jsp?error=Invalid Date!"); } //String [] T = start_time.split(":"); //Time t = Time.valueOf(start_time); //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0); //java.sql.Time t_sql = new java.sql.Date(d.getTime()); preparedStmt.setString(4, start_time + ":00"); preparedStmt.setDate(3, d_sql); } catch (ParseException e) { displayMessage(res, "Invalid Date!" + e.getLocalizedMessage()); } // execute the preparedstatement preparedStmt.execute(); SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1"; ResultSet rs = stmt.executeQuery(SQL); boolean check = false; while (rs.next()) { String db_doctor_id = rs.getString("doctor_id"); String db_date_picked = rs.getString("date"); String db_start_time = rs.getString("start_time"); String db_room_id = rs.getString("room_id"); if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id)) && (start_time == null ? db_start_time == null : (start_time + ":00").equals(db_start_time)) && (room_id == null ? db_room_id == null : room_id.equals(db_room_id)) && (date_picked == null ? db_date_picked == null : date_picked.equals(db_date_picked))) { check = true; //displayMessage(res,"Authentication Success!"); SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)"; for (SessonCustomer sessonCustomer : sessonCustomers) { preparedStmt = connection.prepareStatement(SQL2); preparedStmt.setString(1, rs.getString("session_id")); preparedStmt.setString(2, sessonCustomer.getMobile()); preparedStmt.setInt(3, sessonCustomer.getAppointment_num()); preparedStmt.execute(); } try { connection.close(); } catch (SQLException e) { displayMessage(res, "SQLException"); } res.sendRedirect("./home"); } } if (!check) { try { connection.close(); } catch (SQLException e) { displayMessage(res, "SQLException"); } displayMessage(res, "SQL query Failed!"); } } else { con.showErrormessage(res); } /*res.setContentType("text/html");//setting the content type PrintWriter pw=res.getWriter();//get the stream to write the data //writing html in the stream pw.println("<html><body>"); pw.println("Welcome to servlet: "+username); pw.println("</body></html>"); pw.close();//closing the stream */ } catch (Exception ex) { Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex); displayMessage(res, "Error!" + ex.getLocalizedMessage()); } }
From source file:org.beangle.ems.security.service.UserServiceImpl.java
public void createUser(User creator, User newUser) { newUser.setCreator(creator);//w w w. ja va 2 s. com newUser.setUpdatedAt(new Date(System.currentTimeMillis())); newUser.setCreatedAt(new Date(System.currentTimeMillis())); entityDao.saveOrUpdate(newUser); publish(new UserCreationEvent(Collections.singletonList(newUser))); }
From source file:net.niyonkuru.koodroid.ui.DataDetailFragment.java
private XYMultipleSeriesDataset getBarDataset(Cursor cursor, int x, int maxX) { XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); XYSeries series = new XYSeries(null); Calendar cal = Calendar.getInstance(); CalendarUtils.trimTimestamp(cal);/*from w w w .j ava2s. c om*/ if (cursor.isClosed() || !cursor.moveToFirst()) return null; while (x <= maxX) { double count = 0; if (!cursor.isAfterLast()) { /* cursor has data */ Date rowDate = new Date(cal.getTimeInMillis()); Date currDate = Date.valueOf(cursor.getString(UsagesQuery.DATE)); if (rowDate.equals(currDate)) { count = cursor.getDouble(UsagesQuery.COUNT); cursor.moveToNext(); } } cal.add(Calendar.DAY_OF_YEAR, -1); series.add(x++, count); } dataset.addSeries(series); return dataset; }
From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java
@Override public void massUpdatePredecessors(Integer taskSourceId, final List<TaskPredecessor> predecessors, Integer sAccountId) {/* w w w . j av a 2 s . c om*/ Lock lock = DistributionLockUtil.getLock("task-service" + sAccountId); try { PredecessorMapper predecessorMapper = ApplicationContextUtil.getSpringBean(PredecessorMapper.class); PredecessorExample ex = new PredecessorExample(); ex.createCriteria().andSourceidEqualTo(taskSourceId); predecessorMapper.deleteByExample(ex); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final long now = new GregorianCalendar().getTimeInMillis(); if (lock.tryLock(30, TimeUnit.SECONDS)) { jdbcTemplate.batchUpdate( "INSERT INTO `m_prj_predecessor`(`sourceType`, `descType`, `predestype`,`lagDay`, " + "`sourceId`,`descId`, `createdTime`) VALUES (?, ?, ?, ?, ?, ?, ?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement preparedStatement, int i) throws SQLException { preparedStatement.setString(1, predecessors.get(i).getSourcetype()); preparedStatement.setString(2, predecessors.get(i).getDesctype()); preparedStatement.setString(3, predecessors.get(i).getPredestype()); preparedStatement.setInt(4, predecessors.get(i).getLagday()); preparedStatement.setInt(5, predecessors.get(i).getSourceid()); preparedStatement.setInt(6, predecessors.get(i).getDescid()); preparedStatement.setDate(7, new Date(now)); } @Override public int getBatchSize() { return predecessors.size(); } }); } } catch (Exception e) { throw new MyCollabException(e); } finally { DistributionLockUtil.removeLock("task-service" + sAccountId); lock.unlock(); } }