Example usage for java.util Date getDate

List of usage examples for java.util Date getDate

Introduction

In this page you can find the example usage for java.util Date getDate.

Prototype

@Deprecated
public int getDate() 

Source Link

Document

Returns the day of the month represented by this Date object.

Usage

From source file:mtis.CreateDisplayJson.java

public String getJson(String city, String duration) throws Exception {
    String finalReturn = "";
    JSONArray list = new JSONArray();
    JSONObject finalObj = new JSONObject();
    ArrayList<String> month = new ArrayList<String>();
    month.add("Jan");
    month.add("Feb");
    month.add("Mar");
    month.add("Apr");
    month.add("May");
    month.add("Jun");
    month.add("Jul");
    month.add("Aug");
    month.add("Sep");
    month.add("Oct");
    month.add("Nov");
    month.add("Dec");
    Date d = new Date();
    int dayCount = Integer.parseInt(duration);
    Long dL = d.getTime();/*from   w  w  w  .  ja  va 2 s  .c  o  m*/
    FileReader fr = new FileReader(
            "C:\\Users\\Server\\Documents\\twitterData\\" + city + "\\traffic_data_" + city + "_display.txt");
    BufferedReader br = new BufferedReader(fr);
    String line = br.readLine();
    StringBuffer text = new StringBuffer();
    while (line != null) {
        text.append(line);
        line = br.readLine();
    }
    String textData = text.toString();
    textData = textData.replaceAll("\\n", " ");
    String fullTokens[] = textData.split("\\$\\$\\$");
    for (int i = fullTokens.length - 1; i >= 1; i--) {
        StringTokenizer st = new StringTokenizer(fullTokens[i], "||");
        String dateString = st.nextToken();
        Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(dateString);
        Long dateL = date.getTime();
        //System.out.println(dateL);
        String name = st.nextToken();
        name = name.replaceAll("'", " ");
        if (dL - ((dayCount + 1) * 86400 * 1000) <= dateL && dateL <= dL - ((dayCount) * 86400 * 1000)) {
            //System.out.println("i am in");
            JSONObject js = new JSONObject();
            js.put("userScreenName", name);
            System.out.println(name);
            js.put("userProfilePic", st.nextToken());
            js.put("userId", st.nextToken());
            js.put("statusId", st.nextToken());
            js.put("username", st.nextToken());
            js.put("text", st.nextToken());

            SimpleDateFormat format = new SimpleDateFormat("hh:mm a ");
            //System.out.println(format.format(date));
            //System.out.println(date.getDate()+"-"+month.get(date.getMonth())+" "+format.format(date));              
            //System.out.println(dateL);

            js.put("time", date.getDate() + "-" + month.get(date.getMonth()) + " " + format.format(date));
            list.add(js);
        }
        line = br.readLine();
    }
    finalObj.put("locations", list);
    br.close();
    finalReturn = finalObj.toString();
    System.out.println(finalReturn);
    return finalReturn;
}

From source file:org.ms123.common.data.query.JPASelectBuilderPostgresql.java

protected Object getDate(Object data, Map<String, Object> rule) {
    try {//from   w  w  w.j  ava2s  . c  om
        Date d = new Date();
        try {
            if (data instanceof Long) {
                d = new Date((Long) data);
            } else {
                d = new Date(Long.valueOf((String) rule.get("data")));
            }
        } catch (Exception e) {
            try {
                if (data instanceof String) {
                    d = new SimpleDateFormat(
                            (((String) data).indexOf("T") > 0) ? "yyyy-MM-dd'T'HH:mm" : "yyyy-MM-dd")
                                    .parse((String) data, new ParsePosition(0));
                    if (d == null)
                        d = new Date();
                }
            } catch (Exception e1) {
                System.out.println("E:" + e);
            }
        }
        String op = (String) rule.get("op");
        if (op.equals("eq") || op.equals("ceq") || op.equals("neq")) {
            String day = d.getDate() + "";
            String month = d.getMonth() + "";
            String year = (d.getYear() + 1900) + "";
            data = day + "/" + month + "/" + year;
        } else if (op.equals("in") || op.equals("inn")) {
        } else {
            int paramCount = m_queryBuilder.getParamCount();
            data = ":param" + paramCount;
            System.out.println("param" + paramCount + ":" + d);
            m_queryBuilder.getQueryParams().put("param" + paramCount, d);
            m_queryBuilder.incParamCount();
        }
    } catch (Exception e) {
        e.printStackTrace();
        data = "''";
    }
    return data;
}

From source file:voldemort.store.cachestore.impl.CacheStore.java

public void backup(String path, int threshold) {
    packLock.lock();/*  w  w  w.  ja v a2s  .com*/
    try {
        checkPath(path);
        Date date = new Date();
        String filename = path + "/" + getNamePrefix() + getCurIndex() + "." + date.getMonth() + "."
                + date.getDate() + "." + date.getHours() + "." + date.getMinutes();
        backupTask = new BackupThread(this, curIndex, filename);
        backupTask.run();
        //new BackupThread(this, curIndex, filename).start(threshold);
    } finally {
        packLock.unlock();
    }
}

From source file:com.juick.android.ThreadFragment.java

/**
 * calculate delta times/*from  w ww  . ja va  2s  . c o m*/
 * @param messages
 */
private void preprocessMessages(ArrayList<JuickMessage> messages) {
    if (messages == null || messages.size() == 0)
        return;
    Date prevTime = messages.get(0).Timestamp;
    for (int i = 1; i < messages.size(); i++) {
        JuickMessage message = messages.get(i);
        message.deltaTime = message.Timestamp.getTime() - prevTime.getTime();
        if (message.Timestamp.getDate() != prevTime.getDate()) {
            message.deltaTime = Long.MIN_VALUE;
        }
        prevTime = message.Timestamp;
    }
}

From source file:palamarchuk.smartlife.app.RegisterActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_PICKER:
        Date date = new Date();
        return new DatePickerDialog(this, R.style.AppTheme, new DatePickerDialog.OnDateSetListener() {
            @Override//from   w  w w .j  av a 2  s.  co  m
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
                SimpleDateFormat toServer = new SimpleDateFormat("yyyy-MM-dd");

                Calendar calendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);

                birthDateToServer = toServer.format(calendar.getTime());
                birthDate.setText(sdf.format(calendar.getTime()));
            }
        }, date.getYear() + 1900, date.getMonth(), date.getDate());
    }
    return null;
}

From source file:com.zoho.creator.jframework.XMLParser.java

private static void parseAndSetCalendarRecords(ZCView zcView, Node calendarNode) {

    zcView.setGrouped(true);/*from   w w w .  ja va  2  s  . co m*/
    NodeList eventsList = calendarNode.getChildNodes();
    int year = zcView.getRecordsMonthYear().getTwo() - 1900;
    int month = zcView.getRecordsMonthYear().getOne();

    GregorianCalendar cureentmnthcalendar = new GregorianCalendar();
    Date currentDate = new Date();

    for (int i = 0; i < eventsList.getLength(); i++) {
        Node eventNode = eventsList.item(i);
        NamedNodeMap eventAttrMap = eventNode.getAttributes();
        long recordid = Long.parseLong(eventAttrMap.getNamedItem("id").getNodeValue()); //No I18N
        String title = getChildNodeValue(eventNode, "title"); //eventAttrMap.getNamedItem("title").getNodeValue(); //No I18N
        boolean isAllDay = Boolean.parseBoolean(eventAttrMap.getNamedItem("allDay").getNodeValue()); //No I18N
        // 07/31/2013 08:00:00
        String dateFormat = "MM/dd/yyyy HH:mm:ss"; //No I18N
        if (isAllDay) {
            dateFormat = "MM/dd/yyyy"; //No I18N
        }

        Date startTime = getDateValue(eventAttrMap.getNamedItem("start").getNodeValue(), dateFormat); //No I18N

        ZCRecord record = zcView.getRecord(recordid);

        record.setEventTitle(title);
        if (isAllDay) {
            zcView.setIsAllDay(isAllDay);

            Node endNode = eventAttrMap.getNamedItem("end");//No I18N
            Date endTime = null;
            if (endNode != null) {
                endTime = getDateValue(endNode.getNodeValue(), dateFormat);
            }

            int startDay = -1;
            if (startTime != null) {
                startDay = startTime.getDate();
            }

            int endDay = -1;
            if (endTime != null) {
                endDay = endTime.getDate();
            }

            if (endDay != -1) {

                currentDate.setDate(1);
                currentDate.setMonth(month);
                currentDate.setYear(year);
                currentDate.setMinutes(0);
                currentDate.setHours(0);
                currentDate.setSeconds(0);

                cureentmnthcalendar.setTime(currentDate);

                cureentmnthcalendar.add(cureentmnthcalendar.DAY_OF_MONTH, -6);
                currentDate = cureentmnthcalendar.getTime();

                for (int j = 0; j < 42; j++) {
                    if ((currentDate.getDate() == startTime.getDate()
                            && currentDate.getMonth() == startTime.getMonth()
                            && currentDate.getYear() == startTime.getYear())
                            || (currentDate.after(startTime) && currentDate.before(endTime))
                            || (currentDate.getDate() == endTime.getDate()
                                    && currentDate.getMonth() == endTime.getMonth()
                                    && currentDate.getYear() == endTime.getYear())) {

                        zcView.setEvent(record, currentDate);
                    }
                    cureentmnthcalendar.add(cureentmnthcalendar.DAY_OF_MONTH, 1);
                    currentDate = cureentmnthcalendar.getTime();
                }
                //Collections.sort(eventRecords);
            }

            record.setEventDate(startTime);
        } else {
            // 07/31/2013 08:00:00
            Date endTime = getDateValue(eventAttrMap.getNamedItem("end").getNodeValue(), dateFormat); //No I18N
            record.setStartTime(startTime);
            record.setEndTime(endTime);

            Calendar startCalendar = new GregorianCalendar();
            startCalendar.setTime(startTime);
            startCalendar.set(Calendar.HOUR_OF_DAY, 0);
            startCalendar.set(Calendar.MINUTE, 0);
            startCalendar.set(Calendar.SECOND, 0);
            startCalendar.set(Calendar.MILLISECOND, 0);

            Calendar endCalendar = new GregorianCalendar();
            endCalendar.setTime(endTime);
            endCalendar.set(Calendar.HOUR_OF_DAY, 0);
            endCalendar.set(Calendar.MINUTE, 0);
            endCalendar.set(Calendar.SECOND, 0);
            endCalendar.set(Calendar.MILLISECOND, 0);

            Date eventDate = new Date(startCalendar.getTimeInMillis());
            zcView.setEvent(record, eventDate);
            while ((startCalendar.get(Calendar.YEAR) != endCalendar.get(Calendar.YEAR))
                    || (startCalendar.get(Calendar.MONTH) != endCalendar.get(Calendar.MONTH))
                    || (startCalendar.get(Calendar.DATE) != endCalendar.get(Calendar.DATE))) {
                startCalendar.add(Calendar.DATE, 1);
                eventDate = new Date(startCalendar.getTimeInMillis());
                zcView.setEvent(record, eventDate);
            }
        }
    }

    List<ZCGroup> zcGroups = zcView.getGroups();
    HashMap<Date, List<ZCRecord>> eventsMap = zcView.getEventRecordsMap();
    SortedSet<Date> keys = new TreeSet<Date>(eventsMap.keySet());

    for (Date eventDate : keys) {
        List<ZCRecord> eventRecords = eventsMap.get(eventDate);
        List<String> groupHeaderValues = new ArrayList<String>();
        SimpleDateFormat dateFormat = new SimpleDateFormat(zcView.getDateFormat()); //No I18N
        groupHeaderValues.add(dateFormat.format(eventDate));
        ZCGroup zcGroup = new ZCGroup(groupHeaderValues);
        zcGroups.add(zcGroup);
        for (int i = 0; i < eventRecords.size(); i++) {
            ZCRecord eventRecord = eventRecords.get(i);
            zcGroup.addRecord(eventRecord);
        }
    }
    zcView.sortRecordsForCalendar();

}

From source file:bugs.TestEL.java

/**
 * Test the EL./*ww  w.  jav a 2s.  c om*/
 */
@SuppressWarnings({ "boxing", "deprecation" })
@Test
public void testName() {
    // Arrange
    final SpelExpressionParser parser = new SpelExpressionParser();
    final StandardEvaluationContext context = new StandardEvaluationContext();

    final String spelExpression1 = "testDate.date";
    final String spelExpression2 = "class";
    final String spelExpression3 = "class.name";
    final String spelExpression4 = "name";

    final Date now = new Date();
    final String name = "Testname";

    final TestObject testObject = new TestObject();
    testObject.setTestDate(now);
    testObject.setName(name);

    final SpelExpression exp1 = (SpelExpression) parser.parseExpression(spelExpression1);
    final SpelExpression exp2 = (SpelExpression) parser.parseExpression(spelExpression2);
    final SpelExpression exp3 = (SpelExpression) parser.parseExpression(spelExpression3);
    final SpelExpression exp4 = (SpelExpression) parser.parseExpression(spelExpression4);
    // Act

    final Object value1 = exp1.getValue(context, testObject);

    final Object value2 = exp2.getValue(context, testObject);

    final Object value3 = exp3.getValue(context, testObject);

    Object value4 = null;
    try {
        value4 = exp4.getValue(context, testObject);
    } catch (SpelEvaluationException e) {
        Assert.assertEquals(
                "EL1021E:(pos 0): A problem occurred whilst " + "attempting to access the property 'name': "
                        + "'Unable to access property 'name' through getter'",
                e.getMessage());
        // CSOFF: RegexpSinglelineJava
        System.err.println("Spring-Bug SPR-9017 happens!");
        // CSON: RegexpSinglelineJava
        value4 = name;
    }

    // Assert
    Assert.assertEquals(value1, now.getDate());
    Assert.assertEquals(value2, TestObject.class);
    Assert.assertEquals(value3, TestObject.class.getName());
    Assert.assertEquals(value4, name);

}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java

public void testLoadTable1() throws Exception {
    IPentahoSession session = new StandaloneSession("test");
    KettleSystemListener.environmentInit(session);
    ModelInfo info = createModel();// w w w  .j a v  a 2  s .  c om
    CsvTransformGenerator gen = new CsvTransformGenerator(info, getDatabaseMeta());

    // create the model
    String tableName = info.getStageTableName();
    try {
        gen.execSqlStatement(getDropTableStatement(tableName), getDatabaseMeta(), null);
    } catch (CsvTransformGeneratorException e) {
        // table might not be there yet, it is OK
    }

    // generate the database table
    gen.createOrModifyTable(session);

    // load the table
    loadTable(gen, info, true, session);

    // check the results
    long rowCount = this.getRowCount(tableName);
    assertEquals((long) 235, rowCount);
    DatabaseMeta databaseMeta = getDatabaseMeta();
    assertNotNull(databaseMeta);
    Database database = new Database(databaseMeta);
    assertNotNull(database);
    database.connect();

    Connection connection = null;
    Statement stmt = null;
    ResultSet sqlResult = null;

    try {
        connection = database.getConnection();
        assertNotNull(connection);
        stmt = database.getConnection().createStatement();

        // check the first row
        Date testDate = new Date();
        testDate.setDate(1);
        testDate.setHours(0);
        testDate.setMinutes(0);
        testDate.setMonth(0);
        testDate.setSeconds(0);
        testDate.setYear(110);
        boolean ok = stmt.execute("select * from " + tableName);
        assertTrue(ok);
        sqlResult = stmt.getResultSet();
        assertNotNull(sqlResult);
        ok = sqlResult.next();
        assertTrue(ok);

        // test the values
        assertEquals((long) 3, sqlResult.getLong(1));
        assertEquals(25677.96525, sqlResult.getDouble(2));
        assertEquals((long) 1231, sqlResult.getLong(3));
        assertEquals(testDate.getYear(), sqlResult.getDate(4).getYear());
        assertEquals(testDate.getMonth(), sqlResult.getDate(4).getMonth());
        assertEquals(testDate.getDate(), sqlResult.getDate(4).getDate());
        assertEquals(testDate.getHours(), sqlResult.getTime(4).getHours());
        //    assertEquals( testDate.getMinutes(), ((Date)cells[3]).getMinutes() ); this fails, a bug in the PDI date parsing?
        assertEquals(testDate.getSeconds(), sqlResult.getTime(4).getSeconds());

        //    assertEquals( testDate, cells[3] );
        assertEquals("Afghanistan", sqlResult.getString(5));
        assertEquals((long) 11, sqlResult.getLong(6));
        assertEquals(111.9090909, sqlResult.getDouble(7));
        assertEquals(false, sqlResult.getBoolean(8));
    } finally {
        sqlResult.close();
        stmt.close();
        connection.close();
    }

}

From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java

private List<Encounter> randomizeEncounterDates(List<Obs> patientObsList) {
    Integer flag = 0;/*ww  w .j a v  a2s.  co  m*/
    List<Date> randomizedEncounterDateList = new ArrayList<Date>();
    List<Encounter> en = new ArrayList<Encounter>();
    for (Obs o : patientObsList) {
        en.add(o.getEncounter());
    }
    int year, month, date;
    try {
        for (int i = 0; i < patientObsList.size(); i++) {
            Date d = new Date();
            if (flag == 0) {
                d.setDate(en.get(0).getEncounterDatetime().getDate());
                d.setMonth(en.get(0).getEncounterDatetime().getMonth());
                d.setYear(en.get(0).getEncounterDatetime().getYear());
                flag = 1;
            } else {
                d.setDate(en.get(i - 1).getEncounterDatetime().getDate());
                d.setMonth(en.get(i - 1).getEncounterDatetime().getMonth());
                d.setYear(en.get(i - 1).getEncounterDatetime().getYear());
            }
            year = d.getYear() + 1900;
            month = d.getMonth();
            date = d.getDate();

            //Randomize
            year = randBetween(year + 1, year + 2);
            month = randBetween(month, 12);
            date = randBetween(date, 30);

            //Set date
            d.setYear(year - 1900);
            d.setMonth(month);
            d.setDate(date);
            en.get(i).setEncounterDatetime(d);
            randomizedEncounterDateList.add(d);
        }
    } catch (APIException e) {
        log.error("Exception in randomizing encounter dates", e);
    }
    return en;
}

From source file:org.wurtele.ifttt.watchers.WorkTimesWatcher.java

private void processFile(Path input) {
    logger.info("Updating " + output);

    try (Workbook wb = new XSSFWorkbook();
            OutputStream out = Files.newOutputStream(output, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        Sheet sheet = wb.createSheet("Time Sheet");
        List<WorkDay> days = new ArrayList<>();
        DateFormat df = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mma");
        for (String line : Files.readAllLines(input)) {
            String[] data = line.split(";");
            LocationType type = LocationType.valueOf(data[0].toUpperCase());
            Date time = df.parse(data[1]);
            Date day = DateUtils.truncate(time, Calendar.DATE);
            WorkDay wd = new WorkDay(day);
            if (days.contains(wd))
                wd = days.get(days.indexOf(wd));
            else//  ww  w  .j a va2s  . c  o m
                days.add(wd);
            wd.getTimes().add(new WorkTime(time, type));
        }

        CreationHelper helper = wb.getCreationHelper();
        Font bold = wb.createFont();
        bold.setBoldweight(Font.BOLDWEIGHT_BOLD);

        CellStyle dateStyle = wb.createCellStyle();
        dateStyle.setDataFormat(helper.createDataFormat().getFormat("MMMM d, yyyy"));
        CellStyle timeStyle = wb.createCellStyle();
        timeStyle.setDataFormat(helper.createDataFormat().getFormat("h:mm AM/PM"));
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
        headerStyle.setFont(bold);
        CellStyle totalStyle = wb.createCellStyle();
        totalStyle.setAlignment(CellStyle.ALIGN_RIGHT);

        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("DATE");
        header.getCell(0).setCellStyle(headerStyle);

        Collections.sort(days);
        for (int r = 0; r < days.size(); r++) {
            WorkDay day = days.get(r);
            Row row = sheet.createRow(r + 1);
            row.createCell(0).setCellValue(day.getDate());
            row.getCell(0).setCellStyle(dateStyle);
            Collections.sort(day.getTimes());
            for (int c = 0; c < day.getTimes().size(); c++) {
                WorkTime time = day.getTimes().get(c);
                if (sheet.getRow(0).getCell(c + 1) != null
                        && !sheet.getRow(0).getCell(c + 1).getStringCellValue().equals(time.getType().name())) {
                    throw new Exception("Invalid data");
                } else if (sheet.getRow(0).getCell(c + 1) == null) {
                    sheet.getRow(0).createCell(c + 1).setCellValue(time.getType().name());
                    sheet.getRow(0).getCell(c + 1).setCellStyle(headerStyle);
                }
                row.createCell(c + 1).setCellValue(time.getTime());
                row.getCell(c + 1).setCellStyle(timeStyle);
            }
        }

        int totalCol = header.getLastCellNum();
        header.createCell(totalCol).setCellValue("TOTAL");
        header.getCell(totalCol).setCellStyle(headerStyle);

        for (int r = 0; r < days.size(); r++) {
            sheet.getRow(r + 1).createCell(totalCol).setCellValue(days.get(r).getTotal());
            sheet.getRow(r + 1).getCell(totalCol).setCellStyle(totalStyle);
        }

        for (int c = 0; c <= totalCol; c++) {
            sheet.autoSizeColumn(c);
        }

        wb.write(out);
    } catch (Exception e) {
        logger.error("Failed to update " + output, e);
    }
}