Example usage for java.text DateFormat getDateInstance

List of usage examples for java.text DateFormat getDateInstance

Introduction

In this page you can find the example usage for java.text DateFormat getDateInstance.

Prototype

public static final DateFormat getDateInstance() 

Source Link

Document

Gets the date formatter with the default formatting style for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.dpcsoftware.mn.App.java

public String dateToUser(String pattern, Date date) {
    SimpleDateFormat formater;//w ww. jav  a  2 s.c o  m
    if (pattern == null)
        formater = (SimpleDateFormat) DateFormat.getDateInstance();
    else
        formater = new SimpleDateFormat(pattern, Locale.getDefault());
    return formater.format(date);
}

From source file:op.care.dfn.PnlDFN.java

private void reloadDisplay() {
    /***//from  w ww.j  a  v a2  s  . c o  m
     *               _                 _ ____  _           _
     *      _ __ ___| | ___   __ _  __| |  _ \(_)___ _ __ | | __ _ _   _
     *     | '__/ _ \ |/ _ \ / _` |/ _` | | | | / __| '_ \| |/ _` | | | |
     *     | | |  __/ | (_) | (_| | (_| | |_| | \__ \ |_) | | (_| | |_| |
     *     |_|  \___|_|\___/ \__,_|\__,_|____/|_|___/ .__/|_|\__,_|\__, |
     *                                              |_|            |___/
     */
    initPhase = true;
    synchronized (mapDFN2Pane) {
        SYSTools.clear(mapDFN2Pane);
    }

    synchronized (mapShift2DFN) {
        for (Byte key : mapShift2DFN.keySet()) {
            mapShift2DFN.get(key).clear();
        }
    }

    synchronized (mapShift2Pane) {
        for (Byte key : mapShift2Pane.keySet()) {
            mapShift2Pane.get(key).removeAll();
        }
        mapShift2Pane.clear();
    }

    final boolean withworker = true;
    if (withworker) {

        OPDE.getMainframe().setBlocked(true);
        OPDE.getDisplayManager()
                .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

        cpDFN.removeAll();

        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {

                int progress = 0;
                OPDE.getDisplayManager()
                        .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, 100));

                ArrayList<DFN> listDFNs = DFNTools.getDFNs(resident, jdcDate.getDate());

                synchronized (mapShift2DFN) {
                    for (DFN dfn : listDFNs) {
                        mapShift2DFN.get(dfn.getShift()).add(dfn);
                    }
                }

                // now build the CollapsiblePanes
                for (Byte shift : new Byte[] { DFNTools.SHIFT_ON_DEMAND, DFNTools.SHIFT_VERY_EARLY,
                        DFNTools.SHIFT_EARLY, DFNTools.SHIFT_LATE, DFNTools.SHIFT_VERY_LATE }) {
                    CollapsiblePane cp = createCP4(shift);
                    synchronized (mapShift2Pane) {
                        mapShift2Pane.put(shift, cp);
                        try {
                            mapShift2Pane.get(shift).setCollapsed(shift == DFNTools.SHIFT_ON_DEMAND
                                    || shift != SYSCalendar.whatShiftIs(new Date()));
                        } catch (PropertyVetoException e) {
                            OPDE.debug(e);
                        }
                        progress += 20;
                        OPDE.getDisplayManager().setProgressBarMessage(
                                new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, 100));
                    }
                }
                return null;
            }

            @Override
            protected void done() {
                buildPanel(true);
                initPhase = false;
                OPDE.getDisplayManager().setProgressBarMessage(null);
                OPDE.getMainframe().setBlocked(false);
                OPDE.getDisplayManager().addSubMessage(
                        new DisplayMessage(DateFormat.getDateInstance().format(jdcDate.getDate())));
            }
        };
        worker.execute();

    } else {
        //           buildPanel(true);
    }
    initPhase = false;
}

From source file:org.opendatakit.common.utils.WebUtils.java

/**
 * Parse a string into a datetime value. Tries the common Http formats, the
 * iso8601 format (used by Javarosa), the default formatting from
 * Date.toString(), and a time-only format.
 *
 * @param value/*w w w  .  jav  a 2s .c  om*/
 * @return
 */
public static final Date parseDate(String value) {
    if (value == null || value.length() == 0)
        return null;

    String[] iso8601Pattern = new String[] { PATTERN_ISO8601 };

    String[] localizedParsePatterns = new String[] {
            // try the common HTTP date formats that have time zones
            PATTERN_RFC1123, PATTERN_RFC1036, PATTERN_DATE_TOSTRING };

    String[] localizedNoTzParsePatterns = new String[] {
            // ones without timezones... (will assume UTC)
            PATTERN_ASCTIME };

    String[] tzParsePatterns = new String[] { PATTERN_ISO8601, PATTERN_ISO8601_DATE, PATTERN_ISO8601_TIME };

    String[] noTzParsePatterns = new String[] {
            // ones without timezones... (will assume UTC)
            PATTERN_ISO8601_WITHOUT_ZONE, PATTERN_NO_DATE_TIME_ONLY, PATTERN_YYYY_MM_DD_DATE_ONLY_NO_TIME_DASH,
            PATTERN_GOOGLE_DOCS };

    Date d = null;
    // iso8601 parsing is sometimes off-by-one when JR does it...
    d = parseDateSubset(value, iso8601Pattern, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try to parse with the JavaRosa parsers
    d = DateUtils.parseDateTime(value);
    if (d != null)
        return d;
    d = DateUtils.parseDate(value);
    if (d != null)
        return d;
    d = DateUtils.parseTime(value);
    if (d != null)
        return d;
    // try localized and english text parsers (for Web headers and interactive
    // filter spec.)
    d = parseDateSubset(value, localizedParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedNoTzParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, localizedNoTzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try other common patterns that might not quite match JavaRosa parsers
    d = parseDateSubset(value, tzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    d = parseDateSubset(value, noTzParsePatterns, null, TimeZone.getTimeZone("GMT"));
    if (d != null)
        return d;
    // try the locale- and timezone- specific parsers
    {
        DateFormat formatter = DateFormat.getDateTimeInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    {
        DateFormat formatter = DateFormat.getDateInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    {
        DateFormat formatter = DateFormat.getTimeInstance();
        ParsePosition pos = new ParsePosition(0);
        d = formatter.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    throw new IllegalArgumentException("Unable to parse the date: " + value);
}

From source file:com.xpfriend.fixture.cast.temp.ObjectValidatorBase.java

private Object toDate(String actual) {
    Date date;//from  w w  w . j a va 2  s.c  o  m
    if ((date = parse(DateFormat.getDateInstance(), actual)) != null) {
        return date;
    }
    if ((date = parse(DateFormat.getDateTimeInstance(), actual)) != null) {
        return date;
    }

    TimeZone timeZone = TimeZone.getDefault();
    for (int i = 0; i < DATEFORMATS.length; i++) {
        DateFormat dateFormat = dateFormatter.getDateFormat(DATEFORMATS[i], timeZone);
        if ((date = parse(dateFormat, actual)) != null) {
            return date;
        }
    }
    return actual;
}

From source file:com.predic8.membrane.core.exchange.AbstractExchange.java

@Override
public String toString() {
    return "[time:" + DateFormat.getDateInstance().format(time.getTime()) + ",requestURI:" + request.getUri()
            + "]";
}

From source file:edu.ku.brc.specify.tasks.services.CollectingEventLocalityKMLGenerator.java

/**
 * Generates a KML chunk describing the given collecting event.
 * @param kmlDocument //www.  j a va  2  s.  c o m
 *
 * @param ce the event
 * @param label the label for the event
 * @return the KML string
 */
protected void generatePlacemark(Element kmlDocument, final CollectingEvent ce, final String label) {
    if (ce == null || ce.getLocality() == null || ce.getLocality().getLatitude1() == null
            || ce.getLocality().getLongitude1() == null) {
        return;
    }

    // get all of the important information
    Locality loc = ce.getLocality();
    BigDecimal lat = loc.getLatitude1();
    BigDecimal lon = loc.getLongitude1();

    // get event times
    Calendar start = ce.getStartDate();
    DateFormat dfStart = DateFormat.getDateInstance();

    String startString = "";
    if (start != null) {
        dfStart.setCalendar(start);
        startString = dfStart.format(start.getTime());
    }

    Calendar end = ce.getEndDate();
    DateFormat dfEnd = DateFormat.getDateInstance();

    String endString = "";
    if (end != null) {
        dfEnd.setCalendar(end);
        endString = dfEnd.format(end.getTime());
    }

    // build the placemark
    Element placemark = kmlDocument.addElement("Placemark");
    placemark.addElement("styleUrl").addText("#custom");

    StringBuilder name = new StringBuilder();
    if (label != null) {
        name.append(label);
    }

    if (StringUtils.isNotEmpty(startString)) {
        name.append(startString);
        if (StringUtils.isNotEmpty(endString) && !startString.equals(endString)) {
            name.append(" - ");
            name.append(endString);
        }
    }

    placemark.addElement("name").addText(name.toString());
    // build the fancy HTML popup description

    placemark.addElement("description").addCDATA(generateHtmlDesc(ce));

    GenericKMLGenerator.buildPointAndLookAt(placemark,
            new Pair<Double, Double>(lat.doubleValue(), lon.doubleValue()));
}

From source file:org.iexhub.services.GetPatientDataService.java

@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response getPatientData(@Context HttpHeaders headers) {
    log.info("Entered getPatientData service");

    boolean tls = false;

    tls = (IExHubConfig.getProperty("XdsBRegistryEndpointURI") == null) ? false
            : ((IExHubConfig.getProperty("XdsBRegistryEndpointURI").toLowerCase().contains("https") ? true
                    : false));//from   w  w  w. j  av a  2s.c  om
    GetPatientDataService.testMode = IExHubConfig.getProperty("TestMode", GetPatientDataService.testMode);
    GetPatientDataService.testJSONDocumentPathname = IExHubConfig.getProperty("TestJSONDocumentPathname",
            GetPatientDataService.testJSONDocumentPathname);
    GetPatientDataService.cdaToJsonTransformXslt = IExHubConfig.getProperty("CDAToJSONTransformXSLT",
            GetPatientDataService.cdaToJsonTransformXslt);
    GetPatientDataService.iExHubDomainOid = IExHubConfig.getProperty("IExHubDomainOID",
            GetPatientDataService.iExHubDomainOid);
    GetPatientDataService.iExHubAssigningAuthority = IExHubConfig.getProperty("IExHubAssigningAuthority",
            GetPatientDataService.iExHubAssigningAuthority);
    GetPatientDataService.xdsBRepositoryUniqueId = IExHubConfig.getProperty("XdsBRepositoryUniqueId",
            GetPatientDataService.xdsBRepositoryUniqueId);

    String retVal = "";
    GetPatientDataResponse patientDataResponse = new GetPatientDataResponse();
    StringBuilder jsonOutput = new StringBuilder();

    if (!testMode) {
        try {
            if (xdsB == null) {
                log.info("Instantiating XdsB connector...");
                xdsB = new XdsB(null, null, tls);
                log.info("XdsB connector successfully started");
            }
        } catch (Exception e) {
            log.error("Error encountered instantiating XdsB connector, " + e.getMessage());
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }

        try {
            MultivaluedMap<String, String> headerParams = headers.getRequestHeaders();
            String ssoAuth = headerParams.getFirst("ssoauth");
            log.info("HTTP headers successfully retrieved");

            // Extract patient ID, query start date, and query end date.  Expected format from the client is
            //   "PatientId={0}&LastName={1}&FirstName={2}&MiddleName={3}&DateOfBirth={4}&PatientGender={5}&MotherMaidenName={6}&AddressStreet={7}&AddressCity={8}&AddressState={9}&AddressPostalCode={10}&OtherIDsScopingOrganization={11}&StartDate={12}&EndDate={13}"
            String[] splitPatientId = ssoAuth.split("&LastName=");
            String patientId = (splitPatientId[0].split("=").length == 2) ? splitPatientId[0].split("=")[1]
                    : null;

            String[] parts = splitPatientId[1].split("&");
            String lastName = (parts[0].length() > 0) ? parts[0] : null;
            String firstName = (parts[1].split("=").length == 2) ? parts[1].split("=")[1] : null;
            String middleName = (parts[2].split("=").length == 2) ? parts[2].split("=")[1] : null;
            String dateOfBirth = (parts[3].split("=").length == 2) ? parts[3].split("=")[1] : null;
            String gender = (parts[4].split("=").length == 2) ? parts[4].split("=")[1] : null;
            String motherMaidenName = (parts[5].split("=").length == 2) ? parts[5].split("=")[1] : null;
            String addressStreet = (parts[6].split("=").length == 2) ? parts[6].split("=")[1] : null;
            String addressCity = (parts[7].split("=").length == 2) ? parts[7].split("=")[1] : null;
            String addressState = (parts[8].split("=").length == 2) ? parts[8].split("=")[1] : null;
            String addressPostalCode = (parts[9].split("=").length == 2) ? parts[9].split("=")[1] : null;
            String otherIDsScopingOrganization = (parts[10].split("=").length == 2) ? parts[10].split("=")[1]
                    : null;
            String startDate = (parts[11].split("=").length == 2) ? parts[11].split("=")[1] : null;
            String endDate = (parts[12].split("=").length == 2) ? parts[12].split("=")[1] : null;

            log.info("HTTP headers successfully parsed, now calling XdsB registry...");

            // Determine if a complete patient ID (including OID and ISO specification) was provided.  If not, then append IExHubDomainOid and IExAssigningAuthority...
            if (!patientId.contains("^^^&")) {
                patientId = "'" + patientId + "^^^&" + GetPatientDataService.iExHubDomainOid + "&"
                        + GetPatientDataService.iExHubAssigningAuthority + "'";
            }

            AdhocQueryResponse registryResponse = xdsB.registryStoredQuery(patientId,
                    (startDate != null) ? DateFormat.getDateInstance().format(startDate) : null,
                    (endDate != null) ? DateFormat.getDateInstance().format(endDate) : null);

            log.info("Call to XdsB registry successful");

            // Determine if registry server returned any errors...
            if ((registryResponse.getRegistryErrorList() != null)
                    && (registryResponse.getRegistryErrorList().getRegistryError().length > 0)) {
                for (RegistryError_type0 error : registryResponse.getRegistryErrorList().getRegistryError()) {
                    StringBuilder errorText = new StringBuilder();
                    if (error.getErrorCode() != null) {
                        errorText.append("Error code=" + error.getErrorCode() + "\n");
                    }
                    if (error.getCodeContext() != null) {
                        errorText.append("Error code context=" + error.getCodeContext() + "\n");
                    }

                    // Error code location (i.e., stack trace) only to be logged to IExHub error file
                    patientDataResponse.getErrorMsgs().add(errorText.toString());

                    if (error.getLocation() != null) {
                        errorText.append("Error location=" + error.getLocation());
                    }

                    log.error(errorText.toString());
                }
            }

            // Try to retrieve documents...
            RegistryObjectListType registryObjectList = registryResponse.getRegistryObjectList();
            IdentifiableType[] documentObjects = registryObjectList.getIdentifiable();
            if ((documentObjects != null) && (documentObjects.length > 0)) {
                log.info("Documents found in the registry, retrieving them from the repository...");

                HashMap<String, String> documents = new HashMap<String, String>();
                for (IdentifiableType identifiable : documentObjects) {
                    if (identifiable.getClass().equals(ExtrinsicObjectType.class)) {
                        // Determine if the "home" attribute (homeCommunityId in XCA parlance) is present...
                        String home = ((((ExtrinsicObjectType) identifiable).getHome() != null)
                                && (((ExtrinsicObjectType) identifiable).getHome().getPath().length() > 0))
                                        ? ((ExtrinsicObjectType) identifiable).getHome().getPath()
                                        : null;

                        ExternalIdentifierType[] externalIdentifiers = ((ExtrinsicObjectType) identifiable)
                                .getExternalIdentifier();

                        // Find the ExternalIdentifier that has the "XDSDocumentEntry.uniqueId" value...
                        String uniqueId = null;
                        for (ExternalIdentifierType externalIdentifier : externalIdentifiers) {
                            String val = externalIdentifier.getName().getInternationalStringTypeSequence()[0]
                                    .getLocalizedString().getValue().getFreeFormText();
                            if ((val != null) && (val.compareToIgnoreCase("XDSDocumentEntry.uniqueId") == 0)) {
                                log.info("Located XDSDocumentEntry.uniqueId ExternalIdentifier, uniqueId="
                                        + uniqueId);
                                uniqueId = externalIdentifier.getValue().getLongName();
                                break;
                            }
                        }

                        if (uniqueId != null) {
                            documents.put(uniqueId, home);
                            log.info("Document ID added: " + uniqueId + ", homeCommunityId: " + home);
                        }
                    } else {
                        String home = ((identifiable.getHome() != null)
                                && (identifiable.getHome().getPath().length() > 0))
                                        ? identifiable.getHome().getPath()
                                        : null;
                        documents.put(identifiable.getId().getPath(), home);
                        log.info("Document ID added: " + identifiable.getId().getPath() + ", homeCommunityId: "
                                + home);
                    }
                }

                log.info("Invoking XdsB repository connector retrieval...");
                RetrieveDocumentSetResponse documentSetResponse = xdsB
                        .retrieveDocumentSet(xdsBRepositoryUniqueId, documents, patientId);
                log.info("XdsB repository connector retrieval succeeded");

                // Invoke appropriate map(s) to process documents in documentSetResponse...
                if (documentSetResponse.getRetrieveDocumentSetResponse()
                        .getRetrieveDocumentSetResponseTypeSequence_type0() != null) {
                    DocumentResponse_type0[] docResponseArray = documentSetResponse
                            .getRetrieveDocumentSetResponse().getRetrieveDocumentSetResponseTypeSequence_type0()
                            .getDocumentResponse();
                    if (docResponseArray != null) {
                        jsonOutput.append("{\"Documents\":[");
                        boolean first = true;
                        try {
                            for (DocumentResponse_type0 document : docResponseArray) {
                                if (!first) {
                                    jsonOutput.append(",");
                                }
                                first = false;

                                log.info("Processing document ID="
                                        + document.getDocumentUniqueId().getLongName());

                                String mimeType = docResponseArray[0].getMimeType().getLongName();
                                if (mimeType.compareToIgnoreCase("text/xml") == 0) {
                                    final String filename = this.testOutputPath + "/"
                                            + document.getDocumentUniqueId().getLongName() + ".xml";
                                    log.info("Persisting document to filesystem, filename=" + filename);
                                    DataHandler dh = document.getDocument();
                                    File file = new File(filename);
                                    FileOutputStream fileOutStream = new FileOutputStream(file);
                                    dh.writeTo(fileOutStream);
                                    fileOutStream.close();

                                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                                    Document doc = dBuilder.parse(new FileInputStream(filename));
                                    XPath xPath = XPathFactory.newInstance().newXPath();

                                    //set namespace to xpath
                                    xPath.setNamespaceContext(new NamespaceContext() {
                                        private final String uri = "urn:hl7-org:v3";
                                        private final String prefix = "hl7";

                                        @Override
                                        public String getNamespaceURI(String prefix) {
                                            return this.prefix.equals(prefix) ? uri : null;
                                        }

                                        @Override
                                        public String getPrefix(String namespaceURI) {
                                            return this.uri.equals(namespaceURI) ? this.prefix : null;
                                        }

                                        @Override
                                        public Iterator getPrefixes(String namespaceURI) {
                                            return null;
                                        }
                                    });

                                    NodeList nodes = (NodeList) xPath.evaluate(
                                            "/hl7:ClinicalDocument/hl7:templateId", doc.getDocumentElement(),
                                            XPathConstants.NODESET);

                                    boolean templateFound = false;
                                    if (nodes.getLength() > 0) {
                                        log.info("Searching for /ClinicalDocument/templateId, document ID="
                                                + document.getDocumentUniqueId().getLongName());

                                        for (int i = 0; i < nodes.getLength(); ++i) {
                                            String val = ((Element) nodes.item(i)).getAttribute("root");
                                            if ((val != null) && (val.compareToIgnoreCase(
                                                    "2.16.840.1.113883.10.20.22.1.2") == 0)) {
                                                log.info("/ClinicalDocument/templateId node found, document ID="
                                                        + document.getDocumentUniqueId().getLongName());

                                                log.info("Invoking XSL transform, document ID="
                                                        + document.getDocumentUniqueId().getLongName());

                                                DocumentBuilderFactory factory = DocumentBuilderFactory
                                                        .newInstance();
                                                factory.setNamespaceAware(true);
                                                DocumentBuilder builder = factory.newDocumentBuilder();
                                                Document mappedDoc = builder.parse(new File(filename));
                                                DOMSource source = new DOMSource(mappedDoc);

                                                TransformerFactory transformerFactory = TransformerFactory
                                                        .newInstance();

                                                Transformer transformer = transformerFactory
                                                        .newTransformer(new StreamSource(
                                                                GetPatientDataService.cdaToJsonTransformXslt));
                                                final String jsonFilename = this.testOutputPath + "/"
                                                        + document.getDocumentUniqueId().getLongName()
                                                        + ".json";
                                                File jsonFile = new File(jsonFilename);
                                                FileOutputStream jsonFileOutStream = new FileOutputStream(
                                                        jsonFile);
                                                StreamResult result = new StreamResult(jsonFileOutStream);
                                                transformer.transform(source, result);
                                                jsonFileOutStream.close();

                                                log.info("Successfully transformed CCDA to JSON, filename="
                                                        + jsonFilename);

                                                jsonOutput.append(new String(readAllBytes(get(jsonFilename))));

                                                templateFound = true;
                                            }
                                        }
                                    }

                                    if (!templateFound) {
                                        // Document doesn't match the template ID - add to error list...
                                        patientDataResponse.getErrorMsgs().add(
                                                "Document retrieved doesn't match required template ID - document ID="
                                                        + document.getDocumentUniqueId().getLongName());
                                    }
                                } else {
                                    patientDataResponse.getErrorMsgs()
                                            .add("Document retrieved is not XML - document ID="
                                                    + document.getDocumentUniqueId().getLongName());
                                }
                            }
                        } catch (Exception e) {
                            log.error("Error encountered, " + e.getMessage());
                            throw e;
                        }
                    }
                }

                if (jsonOutput.length() > 0) {
                    jsonOutput.append("]}");
                }
            }
        } catch (Exception e) {
            log.error("Error encountered, " + e.getMessage());
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }
    } else {
        // Return test document when testMode is true
        try {
            retVal = FileUtils.readFileToString(new File(GetPatientDataService.testJSONDocumentPathname));
            return Response.status(Response.Status.OK).entity(retVal).type(MediaType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }
    }

    return Response.status(Response.Status.OK).entity(jsonOutput.toString()).type(MediaType.APPLICATION_JSON)
            .build();
}

From source file:com.eryansky.common.utils.DateUtil.java

/**
 * bool ?2009-08-01//from w w  w.  ja  v a2  s .c o m
 * 
 * @throws ParseException
 */
public static boolean boolcompara(String startdate, String enddate) throws ParseException {

    if (DateFormat.getDateInstance().parse(startdate)
            .compareTo(DateFormat.getDateInstance().parse(startdate)) >= 0) {
        return true;
    } else {
        return false;
    }
}

From source file:biz.wolschon.finance.jgnucash.panels.TaxReportPanel.java

/**
 * @param aFile the file to write to//from   w  w w  . j a va2s .  c o m
 * @param aGran the granularity
 */
private void exportCSV(final File aFile, final ExportGranularities aGran) {
    //TODO: implement CSV-export

    FileWriter fw = null;
    try {
        fw = new FileWriter(aFile);
        // write headers
        List<TransactionSum> sums = mySums;
        fw.write("day");
        for (TransactionSum transactionSum : sums) {
            fw.write(",");
            fw.write(transactionSum.getName());
        }
        fw.write("\n");

        // write data
        GregorianCalendar cal = new GregorianCalendar();
        int add = aGran.getCalendarConstant();
        DateFormat dateFormat = DateFormat.getDateInstance();
        //NumberFormat numberFormat = NumberFormat.getInstance();
        // we do NOT use getCurrencyInstance because it
        // contains a locale-specific currency-symbol
        for (int i = 0; i < 100; i++) {
            Date maxDate = cal.getTime();

            fw.write(dateFormat.format(maxDate));
            int transactionsCounted = 0;
            for (TransactionSum transactionSum : sums) {
                fw.write(",");
                try {
                    transactionSum.setMaxDate(maxDate);
                    FixedPointNumber value = transactionSum.getValue();
                    if (value != null) {
                        //fw.write(numberFormat.format(value));
                        fw.write(value.toString());
                    }
                    transactionsCounted += transactionSum.getTransactionsCounted();
                } catch (JAXBException e) {
                    LOGGER.error("Error calculating one of the TransactionSums", e);
                    fw.write("ERROR");
                }
            }
            fw.write("\n");
            if (transactionsCounted == 0) {
                break;
                // we are walking back in time,
                // when there are no matching transactions,
                // all future runs will we a waste of time.
                // This happens often when add==YEAR
            }

            long old = cal.getTimeInMillis();
            if (add == GregorianCalendar.MONTH) {
                cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
            }
            if (add == GregorianCalendar.YEAR) {
                cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
                cal.set(GregorianCalendar.MONTH, 1);
            }
            // usually we are in the middle of a month,
            // so do not skip the first day of the current
            // month
            if (i != 0 || old == cal.getTimeInMillis() || add == GregorianCalendar.DAY_OF_MONTH) {
                cal.add(add, -1);
            }
        }

        fw.close();
        fw = null;
    } catch (IOException e) {
        LOGGER.error("cannot write csv-file", e);
        JOptionPane.showMessageDialog(this, "Cannot write CSV-file\n" + e.getMessage());
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (IOException e) {
                LOGGER.error("cannot close csv-file", e);
            }
        }
        for (TransactionSum transactionSum : mySums) {
            try {
                transactionSum.setMaxDate(null);
            } catch (JAXBException e) {
                LOGGER.error("cannot set maxDate back to it's original value", e);
            }
        }
    }
}