Java Code Examples for java.text.ParseException

The following are top voted examples for showing how to use java.text.ParseException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: SSIConditional.java   View source code 6 votes vote down vote up
/**
 * Retrieves the expression from the specified arguments and peforms the
 * necessary evaluation steps.
 */
private boolean evaluateArguments(String[] names, String[] values,
        SSIMediator ssiMediator) throws SSIStopProcessingException {
    String expr = getExpression(names, values);
    if (expr == null) {
        throw new SSIStopProcessingException();
        //throw new SsiCommandException( "No expression specified." );
    }
    try {
        ExpressionParseTree tree = new ExpressionParseTree(expr,
                ssiMediator);
        return tree.evaluateTree();
    } catch (ParseException e) {
        //throw new SsiCommandException( "Error parsing expression." );
        throw new SSIStopProcessingException();
    }
}
 
Example 2
Project: unitimes   File: RoomAvailabilityService.java   View source code 6 votes vote down vote up
protected Hashtable<Room, HashSet<TimeBlock>> readResponse(Document response) throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(response.getRootElement().attributeValue("dateFormat","MM/dd/yyyy"), Locale.US);
    SimpleDateFormat timeFormat = new SimpleDateFormat(response.getRootElement().attributeValue("timeFormat","h:mm a"), Locale.US);
    Hashtable<Room, HashSet<TimeBlock>> availability = new Hashtable<Room, HashSet<TimeBlock>>();
    for (Iterator i=response.getRootElement().elementIterator("room");i.hasNext();) {
        Element roomElement = (Element)i.next();
        Room room = new Room(roomElement);
        HashSet<TimeBlock> roomAvailability = availability.get(room);
        if (roomAvailability==null) {
            roomAvailability = new HashSet<TimeBlock>();
            availability.put(room, roomAvailability);
        }
        for (Iterator j=roomElement.elementIterator("event");j.hasNext();) {
            Element eventElement = (Element)j.next();
            EventTimeBlock event = new EventTimeBlock(eventElement, dateFormat, timeFormat);
            roomAvailability.add(event);
        }
    }
    return availability;
}
 
Example 3
Project: ibm-cos-sdk-java   File: DateUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void testIssue233() throws ParseException {
    // https://github.com/aws/aws-sdk-java/issues/233
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    final String edgeCase = "292278994-08-17T07:12:55.807Z";
    Date expected = sdf.parse(edgeCase);
    if (DEBUG)
        System.out.println("date: " + expected);
    String formatted = DateUtils.formatISO8601Date(expected);
    if (DEBUG)
        System.out.println("formatted: " + formatted);
    assertEquals(edgeCase, formatted);
    Date parsed = DateUtils.parseISO8601Date(edgeCase);
    if (DEBUG)
        System.out.println("parsed: " + parsed);
    assertEquals(expected, parsed);
    String reformatted = DateUtils.formatISO8601Date(parsed);
    assertEquals(edgeCase, reformatted);
}
 
Example 4
Project: incubator-netbeans   File: DateTimePickerCellEditor.java   View source code 6 votes vote down vote up
protected Timestamp getValueAsTimestamp(Object value) {
    if (isEmpty(value) || DataViewUtils.isSQLConstantString(value, null)) {
        return new Timestamp(System.currentTimeMillis());
    } else if (value instanceof Timestamp) {
        return (Timestamp) value;
    } else if (value instanceof java.util.Date) {
        return new Timestamp(((java.util.Date) value).getTime());
    } else if (value instanceof java.util.Calendar) {
        return new Timestamp(((java.util.Calendar) value).getTime().getTime());
    } else if (value instanceof Long) {
        return new Timestamp((Long) value);
    } else if (value instanceof String) {
        try {
            return new Timestamp(dateFormat.parse((String) value).getTime());
        } catch (ParseException e) {
            //mLogger.log(Level.SEVERE, e.getMessage(), e.getMessage());
        }
    }

    return new Timestamp(System.currentTimeMillis());
}
 
Example 5
Project: shibboleth-idp-oidc-extension   File: SetRequestedSubjectToResponseContext.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
    try {
        if (idTokenHint != null && idTokenHint.getJWTClaimsSet() != null) {
            log.debug("{} Using requested sub claim value", getLogPrefix());
            getOidcResponseContext().setRequestedSubject(idTokenHint.getJWTClaimsSet().getSubject());
        }
    } catch (ParseException e) {
        log.error("{} error parsing id token hint", getLogPrefix(), e);
        ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_PROFILE_CTX);
        return;
    }
    if (idTokenClaims != null && !idTokenClaims.isEmpty()) {
        for (Entry entry : idTokenClaims) {
            if (IDTokenClaimsSet.SUB_CLAIM_NAME.equals(entry.getClaimName())) {
                log.debug("{} Setting requested sub claim value {} ", getLogPrefix(), entry.getValue());
                getOidcResponseContext().setRequestedSubject(entry.getValue());
            }
        }
    }
}
 
Example 6
Project: CalendarFX   File: IcalParseUtil.java   View source code 6 votes vote down vote up
/**
 * parses a date of the form yyyymmdd or yyyymmdd'T'hhMMss converting from
 * the given timezone to UTC.
 */
public static DateValue parseDateValue(String s, TimeZone tzid)
        throws ParseException {
    Matcher m = DATE_VALUE.matcher(s);
    if (!m.matches()) {
        throw new ParseException(s, 0);
    }
    int year = Integer.parseInt(m.group(1)),
            month = Integer.parseInt(m.group(2)),
            day = Integer.parseInt(m.group(3));
    if (null != m.group(4)) {
        int hour = Integer.parseInt(m.group(4)),
                minute = Integer.parseInt(m.group(5)),
                second = Integer.parseInt(m.group(6));
        boolean utc = null != m.group(7);

        DateValue dv = new DTBuilder(
                year, month, day, hour, minute, second).toDateTime();
        if (!utc && null != tzid) {
            dv = TimeUtils.toUtc(dv, tzid);
        }
        return dv;
    } else {
        return new DTBuilder(year, month, day).toDate();
    }
}
 
Example 7
Project: jerrydog   File: HttpRequestBase.java   View source code 6 votes vote down vote up
/**
 * Return the value of the specified date header, if any; otherwise
 * return -1.
 *
 * @param name Name of the requested date header
 *
 * @exception IllegalArgumentException if the specified header value
 *  cannot be converted to a date
 */
public long getDateHeader(String name) {

    String value = getHeader(name);
    if (value == null)
        return (-1L);

    // Work around a bug in SimpleDateFormat in pre-JDK1.2b4
    // (Bug Parade bug #4106807)
    value += " ";

    // Attempt to convert the date header in a variety of formats
    for (int i = 0; i < formats.length; i++) {
        try {
            Date date = formats[i].parse(value);
            return (date.getTime());
        } catch (ParseException e) {
            ;
        }
    }
    throw new IllegalArgumentException(value);

}
 
Example 8
Project: MyFlightbookAndroid   File: Telemetry.java   View source code 6 votes vote down vote up
Date ParseUTCDate(String s) throws ParseException {
    if (m_pISODate == null) {
        m_pISODate = Pattern.compile("(\\d+)-(\\d+)-(\\d+)T? ?(\\d+):(\\d+):(\\d+\\.?\\d*)Z?", Pattern.CASE_INSENSITIVE);
    }
    Matcher m = m_pISODate.matcher(s);

    if (m.matches()) {
        int year = Integer.parseInt(m.group(1));
        int month = Integer.parseInt(m.group(2));
        int day = Integer.parseInt(m.group(3));
        int hour = Integer.parseInt(m.group(4));
        int minute = Integer.parseInt(m.group(5));
        double second = Double.parseDouble(m.group(6));

        GregorianCalendar gc = UTCDate.UTCCalendar();
        gc.set(year, month - 1, day, hour, minute, (int) second);
        return gc.getTime();
    }
    return new Date();
}
 
Example 9
Project: directory-ldap-api   File: ACIItemParserTest.java   View source code 6 votes vote down vote up
@Test
public void testOrderOfMainACIComponentsDoesNotMatterButMissingsMatter() throws Exception
{
    String spec = "{   itemOrUserFirst userFirst:  { userClasses {  allUsers  , name { \"ou=people,cn=ersin\" }, "
        + "subtree {{ base \"ou=system\" }, { base \"ou=ORGANIZATIONUNIT\","
        + "minimum  1, maximum   2 } } }  , "
        + "userPermissions { { protectedItems{ entry  , attributeType { cn  , ou }  , attributeValue {x=y,m=n,k=l} , "
        + "rangeOfValues (cn=ErsinEr) }  , grantsAndDenials { grantBrowse } } } }, "
        + " identificationTag \"id2\"   , precedence 14 }   ";

    try
    {
        parser.parse( spec );
        fail( "testOrderOfMainACIComponentsDoesNotMatterButMissingsMatter() should not have run this line." );
    }
    catch ( ParseException e )
    {
        assertNotNull( e );
    }
}
 
Example 10
Project: ralasafe   File: SimpleValue.java   View source code 6 votes vote down vote up
public Object getValue(User user, Map context) {
	if (type.equals(STRING)) {
		return value;
	} else if (type.equals(INTEGER)) {
		return new Integer(value);
	} else if (type.equals(FLOAT)) {
		return new Float(value);
	} else if (type.equals(BOOLEAN)) {
		return new Boolean(value);
	} else if (type.equals(DATETIME)) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(value);
		} catch (ParseException e) {
			log.error( "", e );
			throw new RalasafeException(e);
		}
	} else {
		String msg="Not supported value type '" + type + "'.";
		log.error( msg );
		throw new RalasafeException(msg);
	}
}
 
Example 11
Project: ChronoBike   File: DateUtil.java   View source code 6 votes vote down vote up
public static Date formatDate(String csDate, String csFormat, boolean strict)
{
	Date date = null;

	if (csDate != null && csFormat != null && csFormat.length() > 0) 
	{
		try 
		{
			SimpleDateFormat formatter = new SimpleDateFormat(csFormat);
			formatter.setLenient(false);
			date = formatter.parse(csDate);
			if (strict) 
			{
				if (csFormat.length() != csDate.length()) 
				{
					date = null;
				}
			}
		} 
		catch (ParseException e) 
		{
		}
	}
	return date;
}
 
Example 12
Project: CalendarFX   File: IcalSchema.java   View source code 6 votes vote down vote up
public void applyParamSchema(
        String rule, String name, String value, IcalObject out)
        throws ParseException {
    // all elements are allowed extension parameters
    if (EXTENSION_PARAM_NAME_RE.matcher(name).find()) {
        out.getExtParams().put(name, value);
        return;
    }
    // if not an extension, apply the rule
    ruleStack.add(rule);
    try {
        (paramRules.get(rule)).apply(this, name, value, out);
    } finally {
        ruleStack.remove(ruleStack.get(ruleStack.size() - 1));
    }
}
 
Example 13
Project: teamcity-kubernetes-plugin   File: KubeCloudInstanceImpl.java   View source code 6 votes vote down vote up
@NotNull
@Override
public Date getStartedTime() {
    final PodStatus podStatus = myApiConnector.getPodStatus(myPod.getMetadata().getName());
    if(podStatus == null) return myCreationTime;
    try {
        final List<PodCondition> podConditions = podStatus.getConditions();
        if (podConditions != null && !podConditions.isEmpty()) {
            for (PodCondition podCondition : podConditions) {
                if (PodConditionType.valueOf(podCondition.getType()) == PodConditionType.Ready)
                    return myPodTransitionTimeFormat.parse(podCondition.getLastTransitionTime());
            }
        }
        String startTime = podStatus.getStartTime();
        return !StringUtil.isEmpty(startTime) ? myPodStartTimeFormat.parse(startTime) : myCreationTime;
    } catch (ParseException e) {
        throw new KubeCloudException("Failed to get instance start date", e);
    }
}
 
Example 14
Project: directory-ldap-api   File: AttributeUtils.java   View source code 6 votes vote down vote up
/**
 * Parse attribute's options :
 * 
 * options = *( ';' option )
 * option = 1*keychar
 * keychar = 'a'-z' | 'A'-'Z' / '0'-'9' / '-'
 */
private static void parseOptions( char[] str, Position pos ) throws ParseException
{
    while ( Strings.isCharASCII( str, pos.start, ';' ) )
    {
        pos.start++;

        // We have an option
        if ( !Chars.isAlphaDigitMinus( str, pos.start ) )
        {
            // We must have at least one keychar
            throw new ParseException( I18n.err( I18n.ERR_04343 ), pos.start );
        }

        pos.start++;

        while ( Chars.isAlphaDigitMinus( str, pos.start ) )
        {
            pos.start++;
        }
    }
}
 
Example 15
Project: Cryptocurrency-Java-Wrappers   File: Time.java   View source code 6 votes vote down vote up
/**
 * Returns a UNIX timestamp of time specified
 * @param year Year
 * @param month Month
 * @param day Day
 * @param hour Hour
 * @param minute Minute
 * @param timeZone Timezone; e.g. "UTC-5:00"
 * @return Time in UNIX timestamp
 */
public static long unixTimestamp(int year, int month, int day, int hour, int minute, String timeZone) {

	long timeNumber = (year * 100000000L) + (month * 1000000) + (day * 10000) + (hour * 100) + (minute);
	String timeString = Long.toString(timeNumber);
	long unixTime = 0L;

	dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));

	try {
		unixTime = dateFormat.parse(timeString).getTime();
		unixTime /= 1000L;
	} catch(ParseException pe) {
		pe.printStackTrace();
	}

	return unixTime;

}
 
Example 16
Project: Sanxing   File: MyDuration.java   View source code 6 votes vote down vote up
public static long durationFromNowtoB(String B)
{
    //need format of B is yyyy-MM-dd HH:mm:ss
    long diff=0;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try
    {
        Date nowDate=new Date();
        Date endDate=df.parse(B);
        diff = endDate.getTime() - nowDate.getTime();//这样得到的差值是微秒级别
    }
    catch(ParseException e)
    {
        e.printStackTrace();
    }
    return diff;
}
 
Example 17
Project: Calendouer   File: CalendouerActivity.java   View source code 6 votes vote down vote up
boolean needUpdateWeather() {
    int frequency = Integer.parseInt(settingPref.getString("update_frequency", "2"));

    String lastWeatherUpdate = sharedPref.getString("update_datetime", "");
    if (!lastWeatherUpdate.equals("")) {
        try {
            Date lastUpdateDate = df_ymd_hms.parse(lastWeatherUpdate);
            return new Date().getTime() - lastUpdateDate.getTime() > frequency * 60 * 60 * 1000;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    } else {
        return true;
    }
}
 
Example 18
Project: civify-app   File: IssueAdapterTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidEditIssue() throws InterruptedException, ParseException {
    Issue editedIssue = setUpEditedIssue();
    JsonObject edited = mGson.toJsonTree(editedIssue).getAsJsonObject();
    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST);
    mMockWebServer.enqueue(mockResponse);
    IssueSimpleCallback mockCallback = mock(IssueSimpleCallback.class);

    UserAdapter.setCurrentUser(mUser);

    mIssueAdapter.editIssue("issue-auth-token", edited, mockCallback);

    // Test mockCallback.onFailure() is called
    verify(mockCallback, timeout(1000)).onFailure();
}
 
Example 19
Project: LightSIP   File: SIPRequest.java   View source code 6 votes vote down vote up
/**
 * Set the method.
 * 
 * @param method is the method to set.
 * @throws IllegalArgumentException if the method is null
 */
public void setMethod(String method) {
    if (method == null)
        throw new IllegalArgumentException("null method");
    if (this.requestLine == null) {
        this.requestLine = new RequestLine();
    }

    // Set to standard constants to speed up processing.
    // this makes equals compares run much faster in the
    // stack because then it is just identity comparision

    String meth = getCannonicalName(method);
    this.requestLine.setMethod(meth);

    if (this.cSeqHeader != null) {
        try {
            this.cSeqHeader.setMethod(meth);
        } catch (ParseException e) {
        }
    }
}
 
Example 20
Project: letv   File: StringUtils.java   View source code 5 votes vote down vote up
public static String formatTime(String time, String format) {
    if (!(TextUtils.isEmpty(time) || TextUtils.isEmpty(format))) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            time = new SimpleDateFormat(format).format(sdf.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
        }
    }
    return time;
}
 
Example 21
Project: mpay24-java   File: TestPayment.java   View source code 5 votes vote down vote up
@Test
public void testInvoiceBillpayPayment() throws ParseException, PaymentException {
	Payment response = mpay24.payment(getTestPaymentRequest("666", 100l), getInvoiceBillpayTestData(), getCustomer());

	assertEquals("REDIRECT", response.getReturnCode());
	assertNotNull(response.getmPayTid());
}
 
Example 22
Project: uavstack   File: DateTimeHelper.java   View source code 5 votes vote down vote up
/**
 * 判断二个日期相隔的天数,结束时间为null时,,取当前时间
 * 
 * @param startDate
 *            开始时间
 * @param endDate
 *            结束时间
 * @return
 */
public static int getBetweenTodaysStartDateAndEndDate(Date startDate, Date endDate) {

    int betweentoday = 0;
    if (startDate == null) {
        return betweentoday;
    }
    if (endDate == null) {
        Calendar calendar = Calendar.getInstance();
        String year = new Integer(calendar.get(Calendar.YEAR)).toString();
        String month = new Integer((calendar.get(Calendar.MONTH) + 1)).toString();
        String day = new Integer(calendar.get(Calendar.DAY_OF_MONTH)).toString();
        String strtodaytime = year + "-" + month + "-" + day;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            endDate = formatter.parse(strtodaytime);
        }
        catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (endDate.after(startDate)) {
        betweentoday = (int) ((endDate.getTime() - startDate.getTime()) / 86400000);
    }
    else {
        betweentoday = (int) ((startDate.getTime() - endDate.getTime()) / 86400000);
    }
    return betweentoday;
}
 
Example 23
Project: Cashew   File: TimeUtil.java   View source code 5 votes vote down vote up
public static String getFormatTime(String time){
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    long diff = 0;
    try {
        Date publish_date = df.parse(time);
        Date now_date = new Date();
        diff = now_date.getTime() - publish_date.getTime();
        if (diff < 0) {
            return "来自虫洞";
        } else {
            diff /= (1000 * 60);
            if (diff <= 60) {
                return diff + "分钟前";
            }
            diff /= 60;
            if (diff <= 24) {
                return diff + "小时前";
            }
            diff /= 24;
            if (diff < 30) {
                if (diff == 1) return "昨天";
                return diff + "天前";
            }
            DateFormat df_date = new SimpleDateFormat("yyyy-MM-dd");
            return df_date.format(publish_date);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return time;
}
 
Example 24
Project: shareNote   File: EditUserInfoActivity.java   View source code 5 votes vote down vote up
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    try {
        presenter.requestBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
 
Example 25
Project: schulcloud-mobile-android   File: DaysBetweenUtilTest.java   View source code 5 votes vote down vote up
@Test
public void testWeeksBetween() throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
    Date startDate = simpleDateFormat.parse("2017-06-01");
    Date endDate = simpleDateFormat.parse("2017-06-18");
    assertEquals(2, DaysBetweenUtil.weeksBetween(startDate, endDate));
}
 
Example 26
Project: Limitart   File: TimeUtil.java   View source code 5 votes vote down vote up
public static long str2Date(String str) {
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE);
	Date parse = null;
	try {
		parse = format.parse(str);
	} catch (ParseException e) {
		log.error("parse error", e);
		return 0;
	}
	return parse.getTime();
}
 
Example 27
Project: LightSIP   File: AuthenticationHeader.java   View source code 5 votes vote down vote up
public void setIntegrityProtected(String integrityProtected) throws ParseException
{
    if (integrityProtected == null)
        throw new NullPointerException(
            "JAIN-SIP Exception, "
                + " AuthenticationHeader, setIntegrityProtected(), The integrity-protected parameter is null");

    setParameter(INTEGRITY_PROTECTED, integrityProtected);
}
 
Example 28
Project: MyCourses   File: Randevular.java   View source code 5 votes vote down vote up
public Randevular(String rA,String rT,String rY,String tarihAyraci)
{
 randevuAdi=new String(rA);

 try {
 randevuTarihi=new SimpleDateFormat("dd"+tarihAyraci+"MM"+tarihAyraci+"yyyy").parse(rT);
 } catch (ParseException e) {
 e.printStackTrace();
 }

 randevuYeri=new String(rY);
 
}
 
Example 29
Project: pyplyn   File: ArgusExtractProcessor.java   View source code 5 votes vote down vote up
/**
 * Creates an extract result
 *
 * @param time time of data point
 * @param value value of data point
 * @param metric name of data point
 * @return Null if either time or value could not be parsed
 */
private Transmutation createResult(String time, String value, String metric, String endpointId) {
    try {
        ZonedDateTime parsedTime = parseUTCTime(time);
        Number parsedNumber = parseNumber(value);
        return ImmutableTransmutation.of(parsedTime, metric, parsedNumber, parsedNumber,
                ImmutableTransmutation.Metadata.builder().build());

    } catch (DateTimeParseException |ParseException e) {
        logger.warn("No data for {}, endpoint {}; invalid time or value: {}", metric, endpointId, e.getMessage());
        noData();
        return null;
    }
}
 
Example 30
Project: AndroidUtilCode-master   File: TimeUtils.java   View source code 5 votes vote down vote up
/**
 * 将时间字符串转为时间戳
 * <p>time格式为format</p>
 *
 * @param time   时间字符串
 * @param format 时间格式
 * @return 毫秒时间戳
 */
public static long string2Millis(String time, DateFormat format) {
    try {
        return format.parse(time).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return -1;
}
 
Example 31
Project: directory-ldap-api   File: GeneralizedTimeTest.java   View source code 5 votes vote down vote up
/**
 * Tests fraction of a minute.
 */
@Test
public void testFractionOfMinute2() throws ParseException
{
    String gt = "200801021213,125Z";
    GeneralizedTime generalizedTime = new GeneralizedTime( gt );
    String result = generalizedTime.toGeneralizedTime();
    assertEquals( gt, result );
    assertEquals( 7, generalizedTime.getCalendar().get( Calendar.SECOND ) );
    assertEquals( 500, generalizedTime.getCalendar().get( Calendar.MILLISECOND ) );
}
 
Example 32
Project: parabuild-ci   File: Error.java   View source code 5 votes vote down vote up
public Date getTime() {
  try {
    return dateFormatter.parse(content.getProperty(ERROR_TIME));
  } catch (ParseException e) {
    log.warn("Can not parse error time", e);
    return new Date();
  }
}
 
Example 33
Project: amap   File: MIP_DateUtil.java   View source code 5 votes vote down vote up
private static String getPreWeekDay(String dateStr)
{
    
    getPreWeekDay(dateStr);
    Date date = null;
    try
    {
        date = yyyyMMdd.parse(dateStr);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
    return "";
}
 
Example 34
Project: RLibrary   File: TimeUtils.java   View source code 5 votes vote down vote up
/**
 * 将时间字符串转为时间戳
 * <p>time格式为pattern</p>
 *
 * @param time    时间字符串
 * @param pattern 时间格式
 * @return 毫秒时间戳
 */
public static long string2Millis(String time, String pattern) {
    try {
        return new SimpleDateFormat(pattern, Locale.getDefault()).parse(time).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return -1;
}
 
Example 35
Project: RLibrary   File: TimeUtil.java   View source code 5 votes vote down vote up
public static Date getDateFromFormatString(String formatDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
        return sdf.parse(formatDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 36
Project: incubator-netbeans   File: SearchCriteriaPanel.java   View source code 5 votes vote down vote up
private static Date parseDate (String strDate) {
    Date date = null;
    if (strDate != null) {
        for (DateFormat fd : dateFormats) {
            try {
                date = fd.parse(strDate);
            } catch (ParseException ex) { }
        }
    }
    return date;
}
 
Example 37
Project: social-journal   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void success(Result<List<Tweet>> result) {
    Log.d(TAG, "Importing Twitter");
    try {
        for (Tweet tweet : result.data) {
            TwitterPost post = new TwitterPost(uid, getDateFromTweet(tweet), tweet.id);
            mDatabase.getReference("/posts").child(uid).child("tweets").push().setValue(post);
        }

        mDatabase.getReference("/users").child(uid).child("twitter_onboarding").setValue(true);
    } catch (ParseException e) {
        Toast.makeText(getApplicationContext(), "Something went wrong with importing your existing posts", Toast.LENGTH_SHORT).show();
        Log.w(TAG, e);
    }
}
 
Example 38
Project: openjdk-jdk10   File: StringCutter.java   View source code 5 votes vote down vote up
public String next(String regexp) throws ParseException {
    trim();
    Pattern p = Pattern.compile(regexp);
    Matcher m = p.matcher(s);
    if(m.lookingAt()) {
        String r = m.group();
        s = s.substring(r.length());
        trim();
        return r;
    } else
        throw error();
}
 
Example 39
Project: schulcloud-mobile-android   File: DaysBetweenUtilTest.java   View source code 5 votes vote down vote up
@Test
public void testDaysBetween() throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
    Date startDate = simpleDateFormat.parse("2017-06-01");
    Date endDate = simpleDateFormat.parse("2017-06-05");
    assertEquals(4, DaysBetweenUtil.daysBetween(startDate, endDate));
}
 
Example 40
Project: oneops   File: OpsProcMessageProcessor.java   View source code 5 votes vote down vote up
private double diff(String failedEndTS, String failedStartTS) {
    try {
        SimpleDateFormat format = new SimpleDateFormat(CmsConstants.SEARCH_TS_PATTERN);
        return (format.parse(failedEndTS).getTime() - format.parse(failedStartTS).getTime()) / 1000.0;
    } catch (ParseException ignore) {
        return 0;
    }
}