Example usage for java.util Date toString

List of usage examples for java.util Date toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts this Date object to a String of the form:
 dow mon dd hh:mm:ss zzz yyyy
where:
  • dow is the day of the week ( Sun, Mon, Tue, Wed, Thu, Fri, Sat ).

    Usage

    From source file:DataStorageTests.java

    @Test
    public void dateTest() {
        storage = new Storage("{'lower':{}}");
        ZonedDateTime now = ZonedDateTime.now();
        Date dNow = new Date();
        String dNowString = dNow.toString();
        String dateNow = now.toString().split("T")[0];
    
        storage.put("date", now);
        storage.put(new String[] { "lower", "date" }, now);
        storage.put(new String[] { "lower", "otherDate" }, dNow);
    
        Assert.assertEquals(dateNow, storage.get("date"));
        Assert.assertEquals(dateNow, storage.get(new String[] { "lower", "date" }));
        Assert.assertEquals(dNowString, storage.getString(new String[] { "lower", "otherDate" }));
    
        // for testing the parsing of an object with date time objects
        class Inner {
            public ZonedDateTime getDate() {
                return now;
            }/*from w  w  w .j  a v  a  2  s  . com*/
    
            public Date getOtherDate() {
                return dNow;
            }
        }
    
        class Top {
            public ZonedDateTime getDate() {
                return now;
            }
    
            public Inner getInner() {
                return new Inner();
            }
        }
    
        Top test = new Top();
        storage = new Storage(test);
    
        Assert.assertEquals(dateNow, storage.get("date"));
        Assert.assertEquals(dateNow, storage.get(new String[] { "inner", "date" }));
        Assert.assertEquals(dNowString, storage.get(new String[] { "inner", "otherDate" }));
    
        storage = new Storage();
        storage.addModel(test);
    
        Assert.assertEquals(dateNow, storage.get("date"));
        Assert.assertEquals(dateNow, storage.get(new String[] { "inner", "date" }));
        Assert.assertEquals(dNowString, storage.get(new String[] { "inner", "otherDate" }));
    
        storage.put("test", test);
    
        Assert.assertEquals(dateNow, storage.get(new String[] { "test", "date" }));
        Assert.assertEquals(dateNow, storage.get(new String[] { "test", "inner", "date" }));
        Assert.assertEquals(dNowString, storage.get(new String[] { "test", "inner", "otherDate" }));
    
        //array list of objects that have DateTime
        ArrayList<Top> list = new ArrayList<>();
        list.add(new Top());
        list.add(new Top());
    
        storage = new Storage(list);
    
        Assert.assertEquals(dateNow, storage.get(new String[] { "0", "date" }));
        Assert.assertEquals(dateNow, storage.get(new String[] { "1", "inner", "date" }));
        Assert.assertEquals(dNowString, storage.get(new String[] { "0", "inner", "otherDate" }));
        Assert.assertEquals("{\"date\":\"" + dateNow + "\",\"otherDate\":\"" + dNowString + "\"}",
                storage.getAsDataStorage(new String[] { "1", "inner" }).toString());
    }
    

    From source file:com.android.loganalysis.item.GenericItemTest.java

    /**
     * Test that {@link GenericItem#toJson()} returns correctly.
     *//*from w  ww  .j a va 2s  .  c om*/
    public void testToJson() throws JSONException {
        GenericItem item = new GenericItem(new HashSet<String>(
                Arrays.asList("string", "date", "object", "integer", "long", "float", "double", "item", "null")));
        Date date = new Date();
        Object object = new Object();
        NativeCrashItem subItem = new NativeCrashItem();
    
        item.setAttribute("string", "foo");
        item.setAttribute("date", date);
        item.setAttribute("object", object);
        item.setAttribute("integer", 0);
        item.setAttribute("long", 1L);
        item.setAttribute("float", 2.5f);
        item.setAttribute("double", 3.5);
        item.setAttribute("item", subItem);
        item.setAttribute("null", null);
    
        // Convert to JSON string and back again
        JSONObject output = new JSONObject(item.toJson().toString());
    
        assertTrue(output.has("string"));
        assertEquals("foo", output.get("string"));
        assertTrue(output.has("date"));
        assertEquals(date.toString(), output.get("date"));
        assertTrue(output.has("object"));
        assertEquals(object.toString(), output.get("object"));
        assertTrue(output.has("integer"));
        assertEquals(0, output.get("integer"));
        assertTrue(output.has("long"));
        assertEquals(1, output.get("long"));
        assertTrue(output.has("float"));
        assertEquals(2.5, output.get("float"));
        assertTrue(output.has("double"));
        assertEquals(3.5, output.get("double"));
        assertTrue(output.has("item"));
        assertTrue(output.get("item") instanceof JSONObject);
        assertFalse(output.has("null"));
    }
    

    From source file:com.bayesforecast.ingdat.vigsteps.vigmake.VigMakeStep.java

    /**
     * Once the transformation starts executing, the processRow() method is called repeatedly
     * by PDI for as long as it returns true. To indicate that a step has finished processing rows
     * this method must call setOutputDone() and return false;
     * /*from   w  w w .  j a v  a2s  . co  m*/
     * Steps which process incoming rows typically call getRow() to read a single row from the
     * input stream, change or add row content, call putRow() to pass the changed row on 
     * and return true. If getRow() returns null, no more rows are expected to come in, 
     * and the processRow() implementation calls setOutputDone() and returns false to
     * indicate that it is done too.
     * 
     * Steps which generate rows typically construct a new row Object[] using a call to
     * RowDataUtil.allocateRowData(numberOfFields), add row content, and call putRow() to
     * pass the new row on. Above process may happen in a loop to generate multiple rows,
     * at the end of which processRow() would call setOutputDone() and return false;
     * 
     * @param smi the step meta interface containing the step settings
     * @param sdi the step data interface that should be used to store
     * 
     * @return true to indicate that the function should be called again, false if the step is done
     */
    public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    
        // safely cast the step settings (meta) and runtime info (data) to specific implementations 
        //VigMakeStepMeta meta = (VigMakeStepMeta) smi;
        VigMakeStepData data = (VigMakeStepData) sdi;
        HashMap<List<Object>, Item> items = data.items;
        HashMap<Date, Boolean> processedDates = data.processedDates;
        StateTreeAlgorithm insertionAlgo = data.stateInsertionAlgo;
    
        // get incoming row, getRow() potentially blocks waiting for more rows, returns null if no more rows expected
        Object[] r = getRow();
    
        // if no more rows are expected, indicate step is finished and processRow() should not be called again
        if (r == null) {
            setOutputDone();
            return false;
        }
    
        // clone the input row structure and place it in our data object
        data.outputRowMeta = (RowMetaInterface) getInputRowMeta().clone();
        // use meta.getFields() to change it, so it reflects the output row structure 
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, null, null);
    
        // generate new item if it is not present in items.
        List<String> attributeFields = meta.getAttributeFields();
        List<String> idFields = meta.getIdFields();
        List<Object> ids = new ArrayList<Object>();
        List<Object> attributes = new ArrayList<Object>();
        for (String idField : idFields) {
            ids.add(r[getInputRowMeta().indexOfValue(idField)]);
        }
        for (String attributeField : attributeFields) {
            attributes.add(r[getInputRowMeta().indexOfValue(attributeField)]);
        }
        Item item;
    
        if (!items.containsKey(ids)) {
            item = new Item(ids, attributes);
            items.put(ids, item);
        } else {
            item = items.get(ids);
        }
    
        // gets the date field
        String dateField = meta.getDateField();
        int dateIndex = getInputRowMeta().indexOfValue(dateField);
        Date date = getInputRowMeta().getDate(r, dateIndex);
        processedDates.put(date, true);
    
        // generate the new status
        List<String> statusFields = meta.getStatusFields();
        List<Object> status = new ArrayList<Object>();
        for (String statusField : statusFields) {
            status.add(r[getInputRowMeta().indexOfValue(statusField)]);
        }
        State state = new State(status);
        try {
            insertionAlgo.addState(this, item, date, state);
        } catch (StateConflictException e) {
            throw new KettleException("Date conflict between 2 different status.\n" + "Item: " + item.toString()
                    + "\nState" + state.toString() + "\nDate: " + date.toString());
        }
    
        // indicate that processRow() should be called again
        return true;
    }
    

    From source file:org.jasig.portlet.announcements.service.AnnouncementCleanupThread.java

    @Override
    public void run() {
        if (expireThreshold < 0) {
            //A value less than 0 indicates we want to retain all expired announcements
            // and as such there is no reason for the thread to keep running
            this.stopThread();
        }/*from ww  w  . j  a va2  s . c  o m*/
    
        Date now;
        Calendar nowCal = new GregorianCalendar();
        long lastCheckTime = System.currentTimeMillis();
        boolean firstCheck = true;
    
        while (true && keepRunning) {
            now = new Date();
            nowCal.setTime(now);
    
            /**
             * If the current hour of the day = the hour to check AND the current minute of the hour = the
             * minute to check (plus a range of 2 minutes) AND the current time is later than the last
             * time we checked + the required interval
             */
            if (nowCal.get(Calendar.HOUR_OF_DAY) == hourToCheck
                    && nowCal.get(Calendar.MINUTE) <= (minuteToCheck + 1)
                    && (firstCheck || System.currentTimeMillis() > (lastCheckTime + maxCheckIntervalMillis))) {
    
                if (expireThreshold > 0) {
                    log.info("Going to delete old announcements at " + now.toString());
                    announcementService.deleteAnnouncementsPastExpirationThreshold(expireThreshold);
                } else {
                    log.info("Going to delete expired announcements at " + now.toString());
                    announcementService.deleteAnnouncementsPastCurrentTime();
                }
    
                lastCheckTime = System.currentTimeMillis();
                firstCheck = false;
            }
            try {
                log.trace("Waiting to see if we should check the time...");
                sleep(checkInterval * 1000);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
    

    From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeSyncValidator.java

    public boolean snapshotCreation(AmazonEC2Client ec2Client, Volume vol, Date date) {
        if ((date == null) || (ec2Client == null) || (vol == null)) {
            return false;
        }//from   w  w w . j av  a 2 s.  c  om
    
        try {
    
            Collection<Tag> tags_volume = getResourceTags(vol);
    
            String volumeAttachmentInstance = "none";
            try {
                volumeAttachmentInstance = vol.getAttachments().get(0).getInstanceId();
            } catch (Exception e) {
                logger.debug("Volume not attached to instance: " + vol.getVolumeId());
            }
    
            String description = "sync_snapshot " + vol.getVolumeId() + " by Eidetic Synchronizer at "
                    + date.toString() + ". Volume attached to " + volumeAttachmentInstance;
    
            Snapshot current_snap;
            try {
                current_snap = createSnapshotOfVolume(ec2Client, vol, description, numRetries_,
                        maxApiRequestsPerSecond_, uniqueAwsAccountIdentifier_);
            } catch (Exception e) {
                logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId()
                        + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                return false;
            }
    
            try {
                setResourceTags(ec2Client, current_snap, tags_volume, numRetries_, maxApiRequestsPerSecond_,
                        uniqueAwsAccountIdentifier_);
            } catch (Exception e) {
                logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event\"Error\", Error=\"error adding tags to snapshot\", Snapshot_id=\""
                        + current_snap.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                return false;
            }
    
        } catch (Exception e) {
            logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error, Error=\"error in snapshotCreation\", stacktrace=\"" + e.toString()
                    + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\"");
            return false;
        }
    
        return true;
    }
    

    From source file:org.exfio.csyncdroid.resource.LocalCalendar.java

    protected String resourceToString(Resource resource) throws LocalStorageException {
    
        String output = "Event:";
    
        @Cleanup/*  w  w  w . ja va2s. c om*/
        Cursor cursor = null;
        try {
            cursor = providerClient.query(ContentUris.withAppendedId(entriesURI(), resource.getLocalID()),
                    new String[] { /*  0 */ Events.TITLE, Events.EVENT_LOCATION, Events.DESCRIPTION,
                            /*  3 */ Events.DTSTART, Events.DTEND, Events.EVENT_TIMEZONE, Events.EVENT_END_TIMEZONE,
                            Events.ALL_DAY, /*  8 */ Events.STATUS, Events.ACCESS_LEVEL, /* 10 */ Events.RRULE,
                            Events.RDATE, Events.EXRULE, Events.EXDATE, /* 14 */ Events.HAS_ATTENDEE_DATA,
                            Events.ORGANIZER, Events.SELF_ATTENDEE_STATUS, /* 17 */ entryColumnUID(),
                            Events.DURATION, Events.AVAILABILITY, /* 20 */ entryColumnID(), entryColumnRemoteId() },
                    null, null, null);
        } catch (RemoteException e) {
            throw new LocalStorageException("Couldn't find event (" + resource.getLocalID() + ")" + e.getMessage());
        }
    
        if (cursor != null && cursor.moveToNext()) {
    
            output += "\nLocalId: " + cursor.getString(20);
            output += "\nRemoteId: " + cursor.getString(21);
            output += "\nUID: " + cursor.getString(17);
            output += "\nTITLE: " + cursor.getString(0);
            output += "\nEVENT_LOCATION: " + cursor.getString(1);
            output += "\nDESCRIPTION: " + cursor.getString(2);
    
            boolean allDay = cursor.getInt(7) != 0;
            long tsStart = cursor.getLong(3);
            long tsEnd = cursor.getLong(4);
            String duration = cursor.getString(18);
            String tzStart = cursor.getString(5);
            String tzEnd = cursor.getString(6);
    
            Date dtStart = new Date(tsStart);
            Date dtEnd = new Date(tsEnd);
    
            output += "\nALL_DAY: " + allDay;
            output += "\nDTSTART: " + dtStart.toString() + "(" + tsStart + ")";
            output += "\nEVENT_TIMEZONE: " + tzStart;
            output += "\nDTEND: " + dtEnd.toString() + "(" + tsEnd + ")";
            output += "\nEVENT_END_TIMEZONE: " + tzEnd;
            output += "\nDURATION: " + duration;
            output += "\nSTATUS: " + cursor.getString(8);
            output += "\nACCESS_LEVEL: " + cursor.getString(9);
            output += "\nRRULE: " + cursor.getString(10);
            output += "\nRDATE: " + cursor.getString(11);
            output += "\nEXRULE: " + cursor.getString(12);
            output += "\nEXDATE: " + cursor.getString(13);
            output += "\nHAS_ATTENDEE_DATA: " + cursor.getString(14);
            output += "\nORGANIZER: " + cursor.getString(15);
            output += "\nSELF_ATTENDEE_STATUS: " + cursor.getString(16);
            output += "\nAVAILABILITY: " + cursor.getString(19);
        } else {
            throw new LocalStorageException("Invalid cursor while fetching event (" + resource.getLocalID() + ")");
        }
        return output;
    }
    

    From source file:es.tid.fiware.rss.dao.impl.DbeTransactionDaoImpl.java

    @Override
    public List<DbeTransaction> getTransactionBySvcPrdtUserDate(final Long nuServiceId, final Long nuProductId,
            final String enduserid, final Date rqDate) {
        DbeTransactionDaoImpl.LOGGER.debug("Entering getTransactionBySvcPrdtUserDate...");
    
        Criteria criteria = this.getSession().createCriteria(DbeTransaction.class);
        criteria.add(Restrictions.eq("bmService.nuServiceId", nuServiceId));
        if (nuProductId != null) {
            DbeTransactionDaoImpl.LOGGER.debug("product is NOT NULL");
            criteria.add(Restrictions.eq("bmProduct.nuProductId", nuProductId));
    
        }//from w  w  w  . j  a  va 2s  . c  om
        criteria.add(Restrictions.eq("txEndUserId", enduserid));
    
        DbeTransactionDaoImpl.LOGGER.debug("date of request:" + rqDate.toString());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(rqDate);
        int monthreq = calendar.get(Calendar.MONTH);
        DbeTransactionDaoImpl.LOGGER.debug("MONTH ini:" + monthreq);
        int yearreq = calendar.get(Calendar.YEAR);
        DbeTransactionDaoImpl.LOGGER.debug("YEAR ini:" + yearreq);
        int dayreq = calendar.get(Calendar.DATE);
        DbeTransactionDaoImpl.LOGGER.debug("DAY ini:" + dayreq);
    
        Calendar calini = Calendar.getInstance();
        calini.set(Calendar.YEAR, yearreq);
        calini.set(Calendar.MONTH, monthreq);
        calini.set(Calendar.DAY_OF_MONTH, dayreq);
        calini.set(Calendar.HOUR_OF_DAY, 0);
        calini.set(Calendar.MINUTE, 0);
        calini.set(Calendar.SECOND, 0);
        calini.set(Calendar.MILLISECOND, 0);
        Date dateini = calini.getTime();
        DbeTransactionDaoImpl.LOGGER.debug("string date ini:" + dateini.toString());
        DbeTransactionDaoImpl.LOGGER.debug("date ini:" + calini.get(Calendar.YEAR) + "-"
                + calini.get(Calendar.MONTH) + "-" + calini.get(Calendar.DATE) + "-" + calini.get(Calendar.HOUR)
                + "-" + calini.get(Calendar.MINUTE));
    
        Calendar calfin = Calendar.getInstance();
        calfin.set(Calendar.YEAR, yearreq);
        calfin.set(Calendar.MONTH, monthreq);
        calfin.set(Calendar.DAY_OF_MONTH, dayreq);
        calfin.set(Calendar.HOUR_OF_DAY, 23);
        calfin.set(Calendar.MINUTE, 59);
        calfin.set(Calendar.SECOND, 59);
        calfin.set(Calendar.MILLISECOND, 999);
        Date datefin = calfin.getTime();
        DbeTransactionDaoImpl.LOGGER.debug("string date fin:" + datefin.toString());
        DbeTransactionDaoImpl.LOGGER.debug("date fin:" + calfin.get(Calendar.YEAR) + "-"
                + calfin.get(Calendar.MONTH) + "-" + calfin.get(Calendar.DATE) + "-" + calfin.get(Calendar.HOUR)
                + "-" + calfin.get(Calendar.MINUTE));
    
        criteria.add(Restrictions.between("tsRequest", dateini, datefin));
        List<DbeTransaction> result = criteria.list();
        return result;
    
    }
    

    From source file:userinterface.Citizen.CitizenWorkAreaJPanel.java

    public void populateInhalerSensorData() {
        DefaultTableModel dtm = (DefaultTableModel) inhalerTable.getModel();
        dtm.setRowCount(0);/*from  w ww  .j av  a 2  s.c o  m*/
        ArrayList<Date> keyList = new ArrayList<>(
                account.getCitizen().getHealthReport().getAsthamaInhalerSensor().getUsageHistory().keySet());
        Collections.sort(keyList);
        for (Date d : keyList) {
            Area area = account.getCitizen().getHealthReport().getAsthamaInhalerSensor().getUsageHistory().get(d);
            if (null != area) {
                Object row[] = new Object[2];
                row[0] = d.toString();
                row[1] = area;
                dtm.addRow(row);
            }
        }
    }
    

    From source file:org.kuali.ole.docstore.process.RebuildIndexesHandler.java

    public String storeBibInfo(int batchSize) throws Exception {
    
        Date date = new Date();
        String STORAGE_EXCEPTION_FILE_NAME = "BibInfoLoadingErrors-" + date.toString() + ".txt";
        String STORAGE_STATUS_FILE_NAME = "BibInfoLoadingStatus" + date.toString() + ".txt";
    
        long startTime = System.currentTimeMillis();
        bibInfoStatistics = new BibInfoStatistics();
        bibInfoStatistics.setStartDateTime(date);
    
        bibTreeDBUtil.init(0, 0, null);/*from   w w  w .  ja  v a2s. c o m*/
    
        int batchNo = 0;
        int count = bibTreeDBUtil.storeBibInfo(batchSize, filePath, STORAGE_EXCEPTION_FILE_NAME, bibInfoStatistics,
                batchNo);
        long batchStartTime = startTime;
        long batchEndTime = System.currentTimeMillis();
        long totalTimeForBatch = batchEndTime - batchStartTime;
        BatchBibTreeDBUtil.writeStatusToFile(filePath, STORAGE_STATUS_FILE_NAME,
                "Time taken for batch " + totalTimeForBatch);
        while (count > 0) {
            Date batchStartDate = new Date();
            batchStartTime = System.currentTimeMillis();
            bibInfoStatistics.setBatchStartDateTime(batchStartDate);
            count = bibTreeDBUtil.storeBibInfo(batchSize, filePath, STORAGE_EXCEPTION_FILE_NAME, bibInfoStatistics,
                    batchNo++);
            batchEndTime = System.currentTimeMillis();
            Date batchEndDate = new Date();
            bibInfoStatistics.setBatchEndDateTime(batchEndDate);
            bibInfoStatistics.setBatchTotalTime((batchEndTime - batchStartTime));
            totalTimeForBatch = batchEndTime - batchStartTime;
            BatchBibTreeDBUtil.writeStatusToFile(filePath, STORAGE_STATUS_FILE_NAME,
                    "Time taken for batch " + totalTimeForBatch);
        }
    
        long endTime = System.currentTimeMillis();
        Date endDate = new Date();
        bibInfoStatistics.setEndDateTime(endDate);
        long totalTime = endTime - startTime;
        bibInfoStatistics.setTotalTime(totalTime);
        BatchBibTreeDBUtil.writeStatusToFile(filePath, STORAGE_STATUS_FILE_NAME, "Total Time taken " + totalTime);
        return bibInfoStatistics.toString();
    }
    

    From source file:org.alfresco.bm.report.CSVReporter.java

    /**
     * Dump summary data for a test/*  w w w . ja  v  a  2 s. c o m*/
     */
    protected void writeTestDetails(Writer writer, String notes) throws Exception {
        ResultService resultService = getResultService();
        // Get the test result times
        EventRecord firstResult = resultService.getFirstResult();
        long firstEventTime = firstResult == null ? System.currentTimeMillis() : firstResult.getStartTime();
        Date firstEventDate = new Date(firstEventTime);
        EventRecord lastResult = resultService.getLastResult();
        long lastEventTime = lastResult == null ? System.currentTimeMillis() : lastResult.getStartTime();
        Date lastEventDate = new Date(lastEventTime);
        String durationStr = DurationFormatUtils.formatDurationHMS(lastEventTime - firstEventTime);
    
        DBObject testRunObj = getTestService().getTestRunMetadata(test, run);
    
        writer.write("Name:,");
        writer.write(test + "." + run);
        writer.write(NEW_LINE);
        writer.write("Description:,");
        if (testRunObj.get(FIELD_DESCRIPTION) != null) {
            writer.write((String) testRunObj.get(FIELD_DESCRIPTION));
        }
        writer.write(NEW_LINE);
        writer.write("Data:,");
        writer.write(resultService.getDataLocation());
        writer.write(NEW_LINE);
        writer.write("Started:,");
        writer.write(firstEventDate.toString());
        writer.write(NEW_LINE);
        writer.write("Finished:,");
        writer.write(lastEventDate.toString());
        writer.write(NEW_LINE);
        writer.write("Duration:,");
        writer.write("'" + durationStr); // ' is needed for Excel
        writer.write(NEW_LINE);
        writer.write(NEW_LINE);
    
        writer.write("Notes:");
        writer.write(NEW_LINE);
        writer.write(notes.replace(',', ' '));
        writer.write(NEW_LINE);
        writer.write(NEW_LINE);
    }