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: openjdk-jdk10   File: StringCutter.java   Source Code and License 125 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 2
Project: MyFlightbookAndroid   File: Telemetry.java   Source Code and License 5 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 3
Project: monarch   File: NumericQueryJUnitTest.java   Source Code and License 5 votes vote down vote up
private Region createPartitionedRegion(String regionName) throws ParseException {
  Cache cache = CacheUtils.getCache();
  PartitionAttributesFactory prAttFactory = new PartitionAttributesFactory();
  AttributesFactory attributesFactory = new AttributesFactory();
  attributesFactory.setPartitionAttributes(prAttFactory.create());
  RegionAttributes regionAttributes = attributesFactory.create();
  return cache.createRegion(regionName, regionAttributes);
}
 
Example 4
Project: OpenDiabetes   File: UnderThresholdFilterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnderThresholdFilterTest_GLUCOSE_125_00_CGM_CGM_AVAILABLE_CGM_TH() throws ParseException {

    UnderThresholdFilter instance = new UnderThresholdFilter(VaultEntryType.GLUCOSE_CGM, 125.00, FilterType.CGM_AVAILABLE, FilterType.CGM_TH);
    FilterResult result = instance.filter(data);

    List<VaultEntry> filteredData = new ArrayList<>();
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-09:59"), 118));
    //
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-10:29"), 110));
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-10:43"), 105));
    //
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-10:59"), 100));
    //
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-11:14"), 120));
    filteredData.add(new VaultEntry(VaultEntryType.GLUCOSE_CGM, TestFunctions.creatNewDateToCheckFor("2016.04.18-11:29"), 103));

    List<Pair<Date, Date>> timeSeries = new ArrayList<>();
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-09:59"), TestFunctions.creatNewDateToCheckFor("2016.04.18-09:59")));
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-10:29"), TestFunctions.creatNewDateToCheckFor("2016.04.18-10:43")));
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-10:59"), TestFunctions.creatNewDateToCheckFor("2016.04.18-10:59")));
    timeSeries.add(new Pair<>(TestFunctions.creatNewDateToCheckFor("2016.04.18-11:14"), TestFunctions.creatNewDateToCheckFor("2016.04.18-11:29")));
    FilterResult checkForThisResult = new FilterResult(filteredData, timeSeries);

    assertEquals(result.filteredData, checkForThisResult.filteredData);
    assertEquals(result.timeSeries, checkForThisResult.timeSeries);
    //assertEquals(result, checkForThisResult);
}
 
Example 5
Project: directory-ldap-api   File: ACIItemParserTest.java   Source Code and License 5 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 6
Project: OpenDA   File: RtcToolsRuntimeConfigFile.java   Source Code and License 5 votes vote down vote up
public void initialize(File workingDirectory, String[] arguments)
{
	if(arguments.length != 1 && arguments.length != 2 ) {
		throw new RuntimeException(usageString);
	}
	String inputFileName = arguments[0];
	this.outputFileName = inputFileName;
	if (arguments.length > 1) {
		this.outputFileName = arguments[1];
	}

	this.workingDirectory = workingDirectory;
	configTree = new ConfigTree(workingDirectory, inputFileName);
	String startDateString = configTree.getAsString(CONFIG_TREE_ELEMENT_STARTDATE, "");
	String startTimeString = configTree.getAsString(CONFIG_TREE_ELEMENT_STARTTIME, "");
	String endDateString = configTree.getAsString(CONFIG_TREE_ELEMENT_ENDDATE, "");
	String endTimeString = configTree.getAsString(CONFIG_TREE_ELEMENT_ENDTIME, "");

	String startString = startDateString + " " + startTimeString;
	String endString = endDateString + " " + endTimeString;
	double mjdStartTime;
	double mjdEndTime;
	try {
		mjdStartTime = TimeUtils.date2Mjd(startString);
		mjdEndTime = TimeUtils.date2Mjd(endString);
	} catch (ParseException e) {
		throw new RuntimeException("Could not parse start/end date time in file " + new File(workingDirectory, inputFileName));
	}
	exchangeItems = new HashMap<>();
	exchangeItems.put(PROPERTY_STARTTIME, new Flow1DTimeInfoExchangeItem(Flow1DTimeInfoExchangeItem.PropertyId.StartTime, mjdStartTime));
	exchangeItems.put(PROPERTY_STOPTIME, new Flow1DTimeInfoExchangeItem(Flow1DTimeInfoExchangeItem.PropertyId.StopTime, mjdEndTime));
}
 
Example 7
Project: ditb   File: PerfDataGenerator.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException, ParseException {
  if (args.length < 4) {
    StringBuilder sb = new StringBuilder();
    sb.append("current parameters: ");
    for (String one : args) {
      sb.append(one).append(",");
    }
    usage();
    return;
  }
  new PerfDataGenerator(args[0], Integer.valueOf(args[1]), Integer.valueOf(args[2]),
      Integer.valueOf(args[3])).work();
}
 
Example 8
Project: uroborosql   File: DateTimeApiParameterMapperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOffsetTime() throws ParseException {
	DateTimeApiParameterMapper mapper = new DateTimeApiParameterMapper();
	assertThat(mapper.toJdbc(OffsetTime.from(createDateTime("2000/01/01 10:10:10.010")), null, null),
			instanceOf(java.sql.Time.class));
	assertThat(mapper.toJdbc(OffsetTime.from(createDateTime("2000/01/01 10:10:10.010")), null, null),
			is(createTime("10:10:10.010")));
}
 
Example 9
Project: Reer   File: IvyXmlModuleDescriptorParser.java   Source Code and License 5 votes vote down vote up
private void extendsStarted(Attributes attributes) throws ParseException {
    String parentOrganisation = attributes.getValue("organisation");
    String parentModule = attributes.getValue("module");
    String parentRevision = attributes.getValue("revision");
    String location = elvis(attributes.getValue("location"), "../ivy.xml");

    String extendType = elvis(attributes.getValue("extendType"), "all").toLowerCase();
    List<String> extendTypes = Arrays.asList(extendType.split(","));

    ModuleDescriptor parent;
    try {
        LOGGER.debug("Trying to parse included ivy file :{}", location);
        parent = parseOtherIvyFileOnFileSystem(location);
        if (parent != null) {
            //verify that the parsed descriptor is the correct parent module.
            ModuleId expected = IvyUtil.createModuleId(parentOrganisation, parentModule);
            ModuleId pid = parent.getModuleRevisionId().getModuleId();
            if (!expected.equals(pid)) {
                LOGGER.warn("Ignoring parent Ivy file {}; expected {} but found {}", location, expected, pid);
                parent = null;
            }
        }

        // if the included ivy file is not found on file system, tries to resolve using
        // repositories
        if (parent == null) {
            LOGGER.debug("Trying to parse included ivy file by asking repository for module :{}#{};{}",
                parentOrganisation, parentModule, parentRevision);
            parent = parseOtherIvyFile(parentOrganisation, parentModule, parentRevision);
        }
    } catch(Exception e) {
        throw (ParseException) new ParseException("Unable to parse included ivy file for " + parentOrganisation + "#" + parentModule + ";" + parentRevision, 0).initCause(e);
    }

    if (parent == null) {
        throw new ParseException("Unable to parse included ivy file for " + parentOrganisation + "#" + parentModule + ";" + parentRevision, 0);
    }

    mergeWithOtherModuleDescriptor(extendTypes, parent);
}
 
Example 10
Project: ralasafe   File: SimpleValue.java   Source Code and License 5 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: Pluto-Android   File: StringUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 将字符串转位年月日
 * 
 * @param sdate
 * @return
 */
public static Date toDate2(String sdate) {
	try {
		return dateFormater2.get().parse(sdate);
	} catch (ParseException e) {
		return null;
	}
}
 
Example 12
Project: YiZhi   File: DateUtils.java   Source Code and License 5 votes vote down vote up
public static Date str2date(String str, String format) {
    Date date = null;
    try {
        if (str != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(str);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}
 
Example 13
Project: java-coap   File: LinkFormatTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSingle() throws ParseException {
    LinkFormat lf = new LinkFormat("/power");
    lf.setObservable(Boolean.TRUE);
    lf.setResourceType("rt-test", "rt-test2");
    lf.setInterfaceDescription("if-test");
    lf.setMaximumSize(123);
    lf.setResourceInstance("ri-test");
    lf.setExport(Boolean.TRUE);
    lf.setMedia("text/plain");
    lf.setTitle("my title");
    lf.setType("example type");
    lf.setAnchor("/test/anch");
    lf.setContentType((short) 12);
    lf.setOAutobservable(true);

    LinkFormat lf2 = LinkFormatBuilder.parse(lf.toString());

    assertEquals(lf, lf2);
    assertEquals(lf.getUri(), lf2.getUri());
    assertEquals(lf.getContentType(), lf2.getContentType());
    assertEquals(lf.getResourceTypeArray(), lf2.getResourceTypeArray());
    assertEquals(lf.getInterfaceDescriptionArray(), lf2.getInterfaceDescriptionArray());
    assertEquals(lf.isObservable(), lf2.isObservable());
    assertEquals(lf.getMaxSize(), lf2.getMaxSize());
    assertEquals(lf.getResourceInstance(), lf2.getResourceInstance());
    assertEquals(lf.getExport(), lf2.getExport());
    assertEquals(lf.getMedia(), lf2.getMedia());
    assertEquals(lf.getTitle(), lf2.getTitle());
    assertEquals(lf.getType(), lf2.getType());
    assertEquals(lf.getAnchor(), lf2.getAnchor());
    assertEquals(lf.getParam("href"), lf.getUri());
}
 
Example 14
Project: BiglyBT   File: DERUTCTime.java   Source Code and License 5 votes vote down vote up
/**
 * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
 * never encoded. When you're creating one of these objects from scratch, that's
 * what you want to use, otherwise we'll try to deal with whatever gets read from
 * the input stream... (this is why the input format is different from the getTime()
 * method output).
 * <p>
 *
 * @param time the time string.
 */
public DERUTCTime(
    String  time)
{
    this.time = time;
    try
    {
        this.getDate();
    }
    catch (ParseException e)
    {
        throw new IllegalArgumentException("invalid date string: " + e.getMessage());
    }
}
 
Example 15
Project: ChronoBike   File: DateUtil.java   Source Code and License 5 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 16
Project: CalendarFX   File: IcalSchema.java   Source Code and License 5 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 17
Project: teamcity-kubernetes-plugin   File: KubeCloudInstanceImpl.java   Source Code and License 5 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 18
Project: spr   File: SqlUpdates.java   Source Code and License 5 votes vote down vote up
public static boolean updateDocumentos(Documentos documentos, String usuarioResponsable)throws ParseException{
	try {
		Connection conect = ConnectionConfiguration.conectar();
		String query = "update documentos set ";
		PreparedStatement update = null;
		
		String startDate = documentos.getFecha();
	    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
	    java.util.Date date = sdf1.parse(startDate);
		java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());

		if (documentos.getNombre() != "") 		{	query += "nombre= ?, ";			}
		if (documentos.getDescripcion() != "") 	{	query += "descripcion= ?, ";	}
		if (documentos.getFecha() !="") 		{	query += "fecha_valides= ?, ";	}
		
		query += "usuario_responsable= ?, ";
		query = query.substring(0, query.length() - 2);
		query += " where id = ? ";

		int cantCampos = 0;
		update = conect.prepareStatement(query);
		if (documentos.getNombre() != "") 		{	cantCampos++;update.setString(cantCampos, documentos.getNombre());}
		if (documentos.getDescripcion() != "")	{	cantCampos++;update.setString(cantCampos, documentos.getDescripcion());}
		if (documentos.getFecha() !="") 		{	cantCampos++;update.setDate(cantCampos, sqlStartDate);}
		
		cantCampos++;
		update.setString(cantCampos, usuarioResponsable);
		cantCampos++;
		update.setInt(cantCampos, documentos.getId());

		update.execute();
		conect.close();
		return true;
	} catch (SQLException e){e.printStackTrace();
			return false;
	}
}
 
Example 19
Project: arquillian-reporter   File: TestSuiteReportTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNewTestSuiteReportShouldContainStartDate() throws ParseException {
    new DateChecker() {
        @Override
        public String getDateFromReport() {
            return new TestSuiteReport().getExecutionStartTime();
        }
    }.assertThatDateWasCorrectlyCreated();
}
 
Example 20
Project: rulesservice   File: DateTimeDeserializer.java   Source Code and License 5 votes vote down vote up
@Override
public LocalDateTime deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    String datetime = element.getAsString();

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date result = format.parse(datetime);
        return result.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    } catch (ParseException exp) {
        System.err.println("Failed to parse Date:"+ exp);
        return null;
    }
 }
 
Example 21
Project: directory-ldap-api   File: AttributeUtils.java   Source Code and License 5 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 22
Project: Cryptocurrency-Java-Wrappers   File: Time.java   Source Code and License 5 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 23
Project: MyFlightbookAndroid   File: FlightProperty.java   Source Code and License 5 votes vote down vote up
private void FromCursor(Cursor c) {
    _id = c.getInt(c.getColumnIndex("_id"));
    idProp = c.getInt(c.getColumnIndex("idProp"));
    idFlight = c.getInt(c.getColumnIndex("idFlight"));
    idPropType = c.getInt(c.getColumnIndex("idPropType"));
    intValue = c.getInt(c.getColumnIndex("IntValue"));
    boolValue = (intValue != 0);
    decValue = c.getDouble(c.getColumnIndex("DecValue"));
    try {
        dateValue = df.parse(c.getString(c.getColumnIndex("DateValue")));
    } catch (ParseException e) {
        dateValue = null;
    }
    stringValue = c.getString(c.getColumnIndex("StringValue"));
}
 
Example 24
Project: Hydrograph   File: DateFuncitonsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void itShouldReturnDayOfYear() throws ParseException{
    String dateInString = "2011-02-01";
    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateInString);
    Integer dayOfYear =  DateFunctions.getDayOfYear(date);
    Assert.assertEquals(dayOfYear,new Integer(32));
}
 
Example 25
Project: excel-utils   File: ConvertUtils.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object convertIfNeccesary(Object obj, Class<?> type,String dateFormat) throws ParseException {
	if(type.equals(obj.getClass())){
		return obj;
	}
	if(String.class.equals(type)){
		if(Date.class.isAssignableFrom(obj.getClass())){
			SimpleDateFormat format = getDateFormat(dateFormat);
			return format.format((Date)obj);
		}
		return obj.toString();
	}
	if(Number.class.isAssignableFrom(type)){
		if(Number.class.isAssignableFrom(obj.getClass())){
			return NumberUtils.convertNumberToTargetClass((Number)obj, (Class<Number>)type);
		}else if(String.class.equals(obj.getClass())){
			return NumberUtils.parseNumber(obj.toString(), (Class<Number>)type);
		}
	}
	if(ClassUtils.isBaseNumberType(type)){//基本类型之中的数字类型
		return NumberUtils.convertNumberToTargetClass((Number)obj, ClassUtils.getNumberWrapClass(type));
	}
	if(char.class.equals(type) || Character.class.equals(type)){
		if(obj.toString().length() > 0 ){
			return new Character(obj.toString().charAt(0));				
		}
		return null;
	}
	if(String.class.equals(obj.getClass())){
		if(Date.class.equals(type)){	
			SimpleDateFormat simpleDateFormat = getDateFormat(dateFormat);
			return simpleDateFormat.parse(obj.toString());
		}
		if(Boolean.class.equals(type)){
			return Boolean.parseBoolean(obj.toString());
		}
	}
	return null;
}
 
Example 26
Project: ibm-cos-sdk-java   File: DateUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void parseIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.iso8601DateFormat.print(date.getTime());
    assertEquals(formatted, alternative);

    Date expectedDate = sdf.parse(formatted);
    Date actualDate = DateUtils.parseISO8601Date(formatted);
    assertEquals(expectedDate, actualDate);
}
 
Example 27
Project: Sanxing   File: MyDuration.java   Source Code and License 5 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 28
Project: Calendouer   File: CalendouerActivity.java   Source Code and License 5 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 29
Project: iosched-reader   File: TimeUtils.java   Source Code and License 5 votes vote down vote up
public static Date parseTimestamp(String timestamp) {
    for (SimpleDateFormat format : ACCEPTED_TIMESTAMP_FORMATS) {
        // TODO: We shouldn't be forcing the time zone when parsing dates.
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        try {
            return format.parse(timestamp);
        } catch (ParseException ex) {
            continue;
        }
    }

    // All attempts to parse have failed
    return null;
}
 
Example 30
Project: spring-spreadsheet   File: ExcelStreamerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSimpleObject_checkThatDocumentIsAValidZipFile() throws ParseException, IOException {
    final List<SpreadsheetStreamerTest.ObjectExampleDTO> data = Arrays.asList(
            new SpreadsheetStreamerTest.ObjectExampleDTO("field 1", 2, createDate(), true),
            new SpreadsheetStreamerTest.ObjectExampleDTO("field 1 2", 23, createDate(), false)
    );

    byte[] bytes = excelStreamer.toByteArray(spreadsheetConverter.convert(data));
    assertThat(bytes, isActuallyAnExcelFile());
}
 
Example 31
Project: mpay24-java   File: TestPaymentStatus.java   Source Code and License 5 votes vote down vote up
@Test
public void testPaymentStatusUsingTransactionId() throws PaymentException, ParseException {
	String tid = getRandomTransactionId();
	Payment payment = mpay24.payment(getTestPaymentRequest(tid, 1l), getVisaTestData());
	Payment paymentStatus = mpay24.paymentDetails(tid);
	assertNotNull(paymentStatus);
	assertEquals("BILLED", paymentStatus.getState().toString());
	assertEquals("EUR", paymentStatus.getCurrency());
	assertEquals(new BigDecimal(100l), paymentStatus.getAmount());
	assertEquals("CC", paymentStatus.getPaymentType().toString());
	assertNotNull(paymentStatus.getmPayTid());
	assertEquals(tid, paymentStatus.getTransactionId());

}
 
Example 32
Project: openjdk-jdk10   File: NFS4StringPrep.java   Source Code and License 5 votes vote down vote up
private static byte[] prepare(byte[] src, StringPrep prep)
            throws ParseException, UnsupportedEncodingException{
    String s = new String(src, "UTF-8");
    UCharacterIterator iter =  UCharacterIterator.getInstance(s);
    StringBuffer out = prep.prepare(iter,StringPrep.DEFAULT);
    return out.toString().getBytes("UTF-8");
}
 
Example 33
Project: seldon-core   File: TimeUtils.java   Source Code and License 5 votes vote down vote up
@Override
public void merge(JsonElement json, Builder builder) throws InvalidProtocolBufferException {
    try {
        Timestamp value = Timestamps.parse(json.getAsString());
        builder.mergeFrom(value.toByteString());
      } catch (ParseException e) {
        throw new InvalidProtocolBufferException("Failed to parse timestamp: " + json);
      }
}
 
Example 34
Project: lams   File: CronTriggerSupport.java   Source Code and License 5 votes vote down vote up
public static OperableTrigger newTrigger(Map<String, Object> attrMap) throws ParseException {
    CronTriggerImpl result = new CronTriggerImpl();
    result.setCronExpression((String) attrMap.get("cronExpression"));
    if(attrMap.containsKey("timeZone")) {
        result.setTimeZone(TimeZone.getTimeZone((String)attrMap.get("timeZone")));
    }
    TriggerSupport.initializeTrigger(result, attrMap);
    return result;
}
 
Example 35
Project: SOS-The-Healthcare-Companion   File: ReadingTools.java   Source Code and License 5 votes vote down vote up
/**
 * A convenient method for parsing reading value based on user's locale
 *
 * @param reading reading number String
 * @return reading Number
 */
@Nullable
public static Number parseReading(String reading) {
    if (reading == null)
        return null;
    NumberFormat numberFormat = NumberFormat.getInstance();
    try {
        return numberFormat.parse(reading);
    } catch (ParseException e) {
        return null;
    }
}
 
Example 36
Project: safecharge-java   File: RequestUtils.java   Source Code and License 5 votes vote down vote up
/**
 * This method is used to calculate the clientRequestId parameter of a request.
 *
 * @param timestamp the timestamp to generate clientRequestId from. It should be in "yyyyMMddHHmmss" format
 * @return the clientRequestId or -1 if it can't be calculated
 */
public static String calculateClientRequestId(String timestamp) {
    try {
        return String.valueOf(sdf.parse(timestamp)
                .getTime());
    } catch (ParseException e) {
        return "-1";
    }
}
 
Example 37
Project: civify-app   File: IssueAdapterTest.java   Source Code and License 5 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 38
Project: LightSIP   File: MultipartMimeContentImpl.java   Source Code and License 5 votes vote down vote up
private ContentImpl parseBodyPart(String bodyPart) throws ParseException {
  String headers[] = null;
  String bodyContent;
  
  // if a empty line starts the body it means no headers are present
  if (bodyPart.startsWith("\n") || bodyPart.startsWith("\r\n")) {
    bodyContent = bodyPart;
  } else {
    // limit the number of crlf (new lines) we split on, only split the header from
    // the body and don't split on any crlf in the body  
    String[] nextPartSplit = bodyPart.split("\r?\n\r?\n", 2);

    bodyContent = bodyPart;
    
    if (nextPartSplit.length == 2) {
      // since we aren't completely sure the data is a header let's test the first one
      String potentialHeaders[] = nextPartSplit[0].split("\r?\n");
      if (potentialHeaders[0].indexOf(":") > 0) {
        headers = potentialHeaders;
        bodyContent = nextPartSplit[1];
      }
    }
  }
  
  ContentImpl content = new ContentImpl(bodyContent);
  if (headers != null) {
    for (String partHeader : headers) {
      Header header = headerFactory.createHeader(partHeader);
      if (header instanceof ContentTypeHeader) {
        content.setContentTypeHeader((ContentTypeHeader) header);
      } else if (header instanceof ContentDispositionHeader) {
        content.setContentDispositionHeader((ContentDispositionHeader) header);
      } else {
        content.addExtensionHeader(header);
      }
    }
  }
  return content;
}
 
Example 39
Project: ttc2017smartGrids   File: ISO8601DateConverter.java   Source Code and License 5 votes vote down vote up
public Date convert(String value) {
  try {
    return DATE_FORMAT.parse(value);
  } catch (ParseException pe) {
    throw new ParameterException(getErrorString(value, String.format("an ISO-8601 formatted date (%s)", DATE_FORMAT.toPattern())));
  }
}
 
Example 40
Project: DateTimePicker   File: DatePickerSpinnerDelegate.java   Source Code and License 5 votes vote down vote up
/**
 * Parses the given <code>date</code> and in case of success sets the result
 * to the <code>outDate</code>.
 *
 * @return True if the date was parsed.
 */
private boolean parseDate(String date, Calendar outDate) {
    try {
        outDate.setTime(mDateFormat.parse(date));
        return true;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 41
Project: LightSIP   File: SIPRequest.java   Source Code and License 5 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 42
Project: lyra2-java   File: CommandLine.java   Source Code and License 5 votes vote down vote up
public Date convert(String value) {
    try {
        return new SimpleDateFormat("yyyy-MM-dd").parse(value);
    } catch (ParseException e) {
        throw new ParameterException("'" + value + "' is not a yyyy-MM-dd date");
    }
}
 
Example 43
Project: minu-poska-android   File: Event.java   Source Code and License 5 votes vote down vote up
Lesson(JSONObject jsonObject) throws JSONException {
    subject = jsonObject.getString(SUBJECT);
    if (jsonObject.has(DESCRIPTION))
        description = jsonObject.getString(DESCRIPTION);

    if (jsonObject.has(TIME)) try {
        time = dateFormat.parse(jsonObject.getString(TIME));
    } catch (ParseException e) {
        Log.e(TAG, "Failed to parse Lesson time", e);
    }
}
 
Example 44
Project: LightSIP   File: Forker.java   Source Code and License 5 votes vote down vote up
/**
 * Adds a suitable Record-Route header to the given request or response
 *
 * @param r
 * @throws ParseException
 * @throws SipException
 * @throws
 */
private void recordRoute(Message m, String uniqueId) throws ParseException,
        SipException {
    Address me = addressFactory.createAddress("<sip:127.0.0.1:" + port
            + ";id=" + uniqueId + '>');
    if (!nonRFC3261Proxy)
        ((SipURI) me.getURI()).setLrParam();
    RecordRouteHeader rr = headerFactory.createRecordRouteHeader(me);
    m.addFirst(rr);
}
 
Example 45
Project: letv   File: StringUtils.java   Source Code and License 4 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 46
Project: mpay24-java   File: TestPayment.java   Source Code and License 4 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 47
Project: BuddyBook   File: DateUtils.java   Source Code and License 4 votes vote down vote up
public static String formatStringDate(String date){

        String result = "";

        if (date == null) return result;

        DateFormat fmtOut = new SimpleDateFormat(MASK_PUBLISH_OUT, Locale.US);
        DateFormat fmtIn = new SimpleDateFormat(MASK_PUBLISH_IN, Locale.US);


        try {

            Date dataParsed = fmtIn.parse(date);

            result = fmtOut.format(dataParsed);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return result;
    }
 
Example 48
Project: uavstack   File: DateTimeHelper.java   Source Code and License 4 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 49
Project: monarch   File: HashIndexQueryIntegrationTest.java   Source Code and License 4 votes vote down vote up
private void createReplicatedRegion(String regionName) throws ParseException {
  createReplicatedRegion(regionName, true);
}
 
Example 50
Project: BlogBookApp   File: TimeUtils.java   Source Code and License 4 votes vote down vote up
public static long getMillisecondsFromDateString(String dateString, String currentFormat, String timeZone)
        throws ParseException {
    Date date = getDateFromDateString(dateString, currentFormat, timeZone);
    return date.getTime();
}
 
Example 51
Project: Cashew   File: TimeUtil.java   Source Code and License 4 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 52
Project: shareNote   File: EditUserInfoActivity.java   Source Code and License 4 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 53
Project: ibm-cos-sdk-java   File: DateUtilsTest.java   Source Code and License 4 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void invalidDate() throws ParseException {
    final String input = "2014-03-06T14:28:58.000Z.000Z";
    DateUtils.parseISO8601Date(input);
}
 
Example 54
Project: schulcloud-mobile-android   File: DaysBetweenUtilTest.java   Source Code and License 4 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 55
Project: Limitart   File: TimeUtil.java   Source Code and License 4 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 56
Project: LightSIP   File: AuthenticationHeader.java   Source Code and License 4 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 57
Project: arez   File: PreDisposeThrowsExceptionModel.java   Source Code and License 4 votes vote down vote up
@PreDispose
void doStuff()
  throws ParseException
{
}
 
Example 58
Project: MyCourses   File: Randevular.java   Source Code and License 4 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 59
Project: pyplyn   File: ArgusExtractProcessor.java   Source Code and License 4 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 60
Project: AndroidUtilCode-master   File: TimeUtils.java   Source Code and License 4 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;
}