Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:com.redprairie.moca.server.expression.operators.arith.TU_MinusExpression.java

License:Open Source License

private void runTestExpectingDate(String a, String b, String expectedDate) throws MocaException {

    MocaResults res = _moca.executeCommand("publish data where result = " + a + " - " + b);

    RowIterator rowIter = res.getRows();
    rowIter.next();/*from  ww w.java 2 s. c om*/

    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYYMMddHHmmss");

    if (expectedDate == null) {
        assertNull(rowIter.getValue("result"));
    } else {
        Date expected = formatter.parseDateTime(expectedDate).toDate();
        assertEquals(expected, rowIter.getDateTime("result"));
    }
}

From source file:com.redprairie.moca.server.expression.operators.arith.TU_PlusExpression.java

License:Open Source License

private void runTestExpectingDate(String a, String b, String expectedDate) throws MocaException {

    MocaResults res = _moca.executeCommand("publish data where result = " + a + " + " + b);

    RowIterator rowIter = res.getRows();
    rowIter.next();//w  w w . j  a  va 2 s .c  o  m

    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYYMMddHHmmss");

    if (expectedDate == null) {
        assertNull(rowIter.getValue("result"));
    } else {
        Date expected = formatter.parseDateTime(expectedDate).toDate();
        assertEquals(expected, rowIter.getDateTime("result"));
    }
}

From source file:com.redprairie.moca.server.expression.TU_DateFunction.java

License:Open Source License

public void testNormalDate() throws Exception {
    DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    runTest("'20020711112345'", dateFormat.parseDateTime("2002-07-11 11:23:45").toDate());
}

From source file:com.reveldigital.api.util.DateTypeFormatter.java

License:Apache License

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonParseException exception = null;
    final String value = json.getAsString();
    for (DateTimeFormatter format : formats)
        try {//from  www.j  a va  2s . c  o m
            synchronized (format) {
                return format.parseDateTime(value).toDate();
            }
        } catch (IllegalArgumentException e) {
            exception = new JsonParseException(e);
        }
    throw exception;
}

From source file:com.roflcode.fitnessChallenge.FetchFitbitActivities.java

License:Apache License

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    logger = serviceProvider.getLoggerService(FetchFitbitActivities.class);
    logger.debug("get fitbit activities ------------------------------");

    String stackmobUserID = request.getParams().get("stackmob_user_id");
    String startDateStr = request.getParams().get("start_date");
    String endDateStr = request.getParams().get("end_date");
    if (endDateStr == "") {
        endDateStr = startDateStr;//from   ww w. jav  a  2 s .c  o m
    }

    if (stackmobUserID == null || stackmobUserID.isEmpty()) {
        HashMap<String, String> errParams = new HashMap<String, String>();
        errParams.put("error", "stackmobUserID was empty or null");
        return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request
    }

    FitbitApiClientAgent agent = AgentInitializer.GetInitializedAgent(serviceProvider, stackmobUserID);
    if (agent == null) {
        HashMap<String, String> errParams = new HashMap<String, String>();
        errParams.put("error", "could not initialize fitbit client agent");
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errParams); // http 500 internal error
    }

    HashMap<String, String> credentials = AgentInitializer.GetStoredFitbitCredentials(serviceProvider,
            stackmobUserID);
    String fitbitUserID = credentials.get("fitbituserid");
    LocalUserDetail user = new LocalUserDetail(stackmobUserID);
    FitbitUser fitbitUser = new FitbitUser(fitbitUserID);
    //LocalDate today = new LocalDate(DateTimeZone.UTC);

    DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
    DateTime dt = formatter.parseDateTime(startDateStr);
    LocalDate startDate = new LocalDate(dt);
    dt = formatter.parseDateTime(endDateStr);
    LocalDate endDate = new LocalDate(dt);

    //TimeZone tz = TimeZone.getTimeZone("GMT-8:00");
    //LocalDate today = new LocalDate(DateTimeZone.forTimeZone(tz));
    //LocalDate today = new LocalDate(DateTimeZone.forTimeZone(tz));
    //LocalDate yesterday = today.minusDays(1);

    logger.debug("entering date loop " + startDate.toString() + " end: " + endDate.toString());
    for (LocalDate date = startDate; date.isBefore(endDate) || date.isEqual(endDate); date = date.plusDays(1)) {
        logger.debug("date: " + date.toString());

        Activities activities;

        try {
            activities = agent.getActivities(user, fitbitUser, date);
        } catch (FitbitAPIException ex) {
            logger.error("failed to get activities", ex);
            HashMap<String, String> errParams = new HashMap<String, String>();
            errParams.put("error", "could not get activities");
            return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errParams); // http 500 internal error
        }

        ActivitiesSummary summary = activities.getSummary();
        //          private Integer floors = null;
        //          private Double elevation = null;
        //          private List<ActivityDistance> distances;

        DataService dataService = serviceProvider.getDataService();

        DateMidnight dateMidnight = date.toDateMidnight();
        long millis = dateMidnight.getMillis();

        List<SMCondition> query;
        List<SMObject> result;

        // build a query
        query = new ArrayList<SMCondition>();
        query.add(new SMEquals("theusername", new SMString(stackmobUserID)));
        query.add(new SMEquals("activity_date", new SMInt(millis)));

        // execute the query
        try {
            boolean newActivity = false;
            SMValue activityId;
            result = dataService.readObjects("activity", query);

            SMObject activityObject;

            //activity was in the datastore, so update
            if (result != null && result.size() == 1) {
                activityObject = result.get(0);
                List<SMUpdate> update = new ArrayList<SMUpdate>();
                update.add(new SMSet("active_score", new SMInt((long) summary.getActiveScore())));
                update.add(new SMSet("steps", new SMInt((long) summary.getSteps())));
                update.add(new SMSet("floors", new SMInt((long) summary.getFloors())));
                update.add(new SMSet("sedentary_minutes", new SMInt((long) summary.getSedentaryMinutes())));
                update.add(new SMSet("lightly_active_minutes",
                        new SMInt((long) summary.getLightlyActiveMinutes())));
                update.add(
                        new SMSet("fairly_active_minutes", new SMInt((long) summary.getFairlyActiveMinutes())));
                update.add(new SMSet("very_active_minutes", new SMInt((long) summary.getVeryActiveMinutes())));
                activityId = activityObject.getValue().get("activity_id");
                logger.debug("update object");
                dataService.updateObject("activity", activityId, update);
                logger.debug("updated object");
            } else {
                Map<String, SMValue> activityMap = new HashMap<String, SMValue>();
                activityMap.put("theusername", new SMString(stackmobUserID));
                activityMap.put("activity_date", new SMInt(millis));
                activityMap.put("activity_date_str", new SMString(date.toString()));
                activityMap.put("active_score", new SMInt((long) summary.getActiveScore()));
                activityMap.put("steps", new SMInt((long) summary.getSteps()));
                activityMap.put("floors", new SMInt((long) summary.getFloors()));
                activityMap.put("sedentary_minutes", new SMInt((long) summary.getSedentaryMinutes()));
                activityMap.put("lightly_active_minutes", new SMInt((long) summary.getLightlyActiveMinutes()));
                activityMap.put("fairly_active_minutes", new SMInt((long) summary.getFairlyActiveMinutes()));
                activityMap.put("very_active_minutes", new SMInt((long) summary.getVeryActiveMinutes()));

                activityObject = new SMObject(activityMap);
                logger.debug("create object");
                activityObject = dataService.createObject("activity", activityObject);
                logger.debug("created object");
                activityId = activityObject.getValue().get("activity_id");
                newActivity = true;
            }

        } catch (InvalidSchemaException e) {
            HashMap<String, String> errMap = new HashMap<String, String>();
            errMap.put("error", "invalid_schema");
            errMap.put("detail", e.toString());
            return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
        } catch (DatastoreException e) {
            HashMap<String, String> errMap = new HashMap<String, String>();
            errMap.put("error", "datastore_exception");
            errMap.put("detail", e.toString());
            return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
        } catch (Exception e) {
            HashMap<String, String> errMap = new HashMap<String, String>();
            errMap.put("error", "unknown");
            errMap.put("detail", e.toString());
            return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
        }
    }
    Map<String, Object> returnMap = new HashMap<String, Object>();
    returnMap.put("success?", "think so");
    //      returnMap.put("activity_id", activityId);
    //      returnMap.put("newActivity", newActivity);
    //returnMap.put("activitiesJson", activities);
    logger.debug("completed get activities");
    return new ResponseToProcess(HttpURLConnection.HTTP_OK, returnMap);
}

From source file:com.sam.moca.util.AppUtils.java

License:Open Source License

private void setupVersionData() {
    InputStream in = AppUtils.class.getResourceAsStream("/com/redprairie/moca/resources/build.properties");

    Properties buildProperties = new Properties();
    if (in != null) {
        try {/*from   w w  w  .ja  v a2s.  c o  m*/
            buildProperties.load(in);
        } catch (InterruptedIOException e) {
            throw new MocaInterruptedException(e);
        } catch (IOException e) {
            // Use default if unable to load properties
        } finally {
            try {
                in.close();
            } catch (IOException ignore) {
            }
        }
    }

    String releaseVersion = buildProperties.getProperty("releaseVersion");
    if (releaseVersion == null) {
        releaseVersion = "2013.2.2.15";
    }
    try {
        DateTimeFormatter inDate = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter outDate = DateTimeFormat.forPattern("MMM d yyyy");

        _fullVersion = "Build date: " + outDate.print(inDate.parseDateTime(releaseVersion));
    } catch (IllegalArgumentException e) {
        // We built with release=Y (probably), just return the version
        String[] splitVersion = releaseVersion.split("\\.");
        // Safety check
        if (splitVersion.length > 2) {
            _majorMinorRevision = splitVersion[0] + "." + splitVersion[1];
        }
        _fullVersion = releaseVersion;
    }
}

From source file:com.sam_chordas.android.stockhawk.app.utils.DateTimeUtils.java

License:Apache License

private static DateTime getDateTimeFromPattern(String inputPattern, String date) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern(inputPattern);
    return formatter.parseDateTime(date);
}

From source file:com.sonicle.webtop.calendar.Service.java

License:Open Source License

public void processExportForErp(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    UserProfile up = getEnv().getProfile();

    try {//from w  ww. ja v a2s . c  om
        String op = ServletUtils.getStringParameter(request, "op", true);
        if (op.equals("do")) {
            String fromDate = ServletUtils.getStringParameter(request, "fromDate", true);
            String toDate = ServletUtils.getStringParameter(request, "toDate", true);

            DateTimeFormatter ymd = DateTimeUtils.createYmdFormatter(up.getTimeZone());
            erpWizard = new ErpExportWizard();
            erpWizard.fromDate = ymd.parseDateTime(fromDate).withTimeAtStartOfDay();
            erpWizard.toDate = DateTimeUtils.withTimeAtEndOfDay(ymd.parseDateTime(toDate));

            LogEntries log = new LogEntries();
            File file = WT.createTempFile();

            try {
                DateTimeFormatter ymd2 = DateTimeUtils.createFormatter("yyyyMMdd", up.getTimeZone());
                DateTimeFormatter ymdhms = DateTimeUtils.createFormatter("yyyy-MM-dd HH:mm:ss",
                        up.getTimeZone());

                try (FileOutputStream fos = new FileOutputStream(file)) {
                    log.addMaster(new MessageLogEntry(LogEntry.Level.INFO, "Started on {0}",
                            ymdhms.print(new DateTime())));
                    manager.exportEvents(log, erpWizard.fromDate, erpWizard.toDate, fos);
                    log.addMaster(new MessageLogEntry(LogEntry.Level.INFO, "Ended on {0}",
                            ymdhms.print(new DateTime())));
                    erpWizard.file = file;
                    erpWizard.filename = MessageFormat.format(ERP_EXPORT_FILENAME, up.getDomainId(),
                            ymd2.print(erpWizard.fromDate), ymd2.print(erpWizard.fromDate), "csv");
                    log.addMaster(
                            new MessageLogEntry(LogEntry.Level.INFO, "File ready: {0}", erpWizard.filename));
                    log.addMaster(new MessageLogEntry(LogEntry.Level.INFO, "Operation completed succesfully"));
                    new JsonResult(new JsWizardData(log.print())).printTo(out);
                }
            } catch (Throwable t) {
                logger.error("Error generating export", t);
                file.delete();
                new JsonResult(new JsWizardData(log.print())).setSuccess(false).printTo(out);
            }
        }

    } catch (Exception ex) {
        logger.error("Error in ExportForErp", ex);
        new JsonResult(false, ex.getMessage()).printTo(out);
    }
}

From source file:com.sonicle.webtop.core.bol.model.SyncDevice.java

License:Open Source License

public SyncDevice(String device, String user, String lastSync) {
    this.device = device;
    this.user = user;
    if (StringUtils.isBlank(lastSync)) {
        this.lastSync = null;
    } else {/*w  w w .  jav a  2  s . c  o  m*/
        try {
            DateTimeFormatter fmt = DateTimeUtils.createYmdHmFormatter(WT.getSystemTimeZone());
            this.lastSync = fmt.parseDateTime(lastSync);
        } catch (UnsupportedOperationException | IllegalArgumentException ex) {
            this.lastSync = null;
        }
    }
}

From source file:com.sonicle.webtop.vfs.bol.js.JsSharingLink.java

License:Open Source License

public static SharingLink createSharingLink(JsSharingLink js, DateTimeZone profileTz) {
    DateTimeFormatter ymdHmsFmt = DateTimeUtils.createYmdHmsFormatter(profileTz);

    SharingLink bean = new SharingLink();
    bean.setLinkId(js.linkId);//from   www.  j a  v  a2 s. c o m
    bean.setType(js.type);
    if (!StringUtils.isBlank(js.expirationDate)) {
        DateTime dt = ymdHmsFmt.parseDateTime(js.expirationDate);
        bean.setExpiresOn(DateTimeUtils.withTimeAtEndOfDay(dt));
    }
    bean.setAuthMode(js.authMode);
    bean.setPassword(js.password);
    return bean;
}