Java Code Examples for java.text.SimpleDateFormat.parse()

The following are Jave code examples for showing how to use parse() of the java.text.SimpleDateFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: amap   File: MIP_CalendarUtil2.java   View Source Code Vote up 7 votes
public static int getWeekByYear(String dateStr)
{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try
    {
        date = sdf.parse(dateStr);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    
    int i = calendar.get(Calendar.WEEK_OF_YEAR);
    return i;
}
 
Example 2
Project: androidtools   File: CustomDatePicker.java   View Source Code Vote up 6 votes
/**
 * Verify that the string is a valid date format.
 */
private boolean isValidDate(String date, String template) {
    boolean convertSuccess = true;
    // Specified date format
    SimpleDateFormat format = new SimpleDateFormat(template, Locale.CHINA);
    try {
        // Set lenient to false., otherwise SimpleDateFormat will validate the date more loosely,
        // for example, 2015/02/29 will be accepted and converted to 2015/03/01.
        format.setLenient(false);
        format.parse(date);
    } catch (Exception e) {
        // If throw, java.text.ParseException, or NullPointerException,
        // it means the format is wrong.
        convertSuccess = false;
    }
    return convertSuccess;
}
 
Example 3
Project: Renrentou   File: TimeUtils.java   View Source Code Vote up 6 votes
public static Date str2Date(String str, String format) {
     if (str == null || str.length() == 0) {
         return null;
     }
     if (format == null || format.length() == 0) {
         format = "yyyy-MM-dd HH:mm:ss";
     }
     Date date = null;
     try {
         SimpleDateFormat sdf = new SimpleDateFormat(format);
         date = sdf.parse(str);

     } catch (Exception e) {
Log.e("TimeUtil",e.toString());
     }
     return date;

 }
 
Example 4
Project: quartz-web   File: DateUtils.java   View Source Code Vote up 5 votes
public static Date parse(String date) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        return format.parse(date);
    } catch (ParseException e) {
        return null;
    }
}
 
Example 5
Project: uavstack   File: DateTimeHelper.java   View Source Code Vote up 5 votes
public static Date getNowTime() {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dateStr = dateFormat(date);
        try {
            date = format.parse(dateStr);
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
 
Example 6
Project: javaOIDCMsg   File: GoogleJwtCreatorTest.java   View Source Code Vote up 5 votes
@Test
public void testGoogleJwtCreatorExpTimeHasPassed() throws Exception {
    thrown.expect(TokenExpiredException.class);
    thrown.expectMessage("The Token has expired on Wed Oct 29 00:00:00 PDT 2014.");

    String myDate = "2014/10/29";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    Date date = sdf.parse(myDate);
    long expLong = date.getTime();
    Date expDate = new Date(expLong);

    Algorithm algorithm = Algorithm.HMAC256("secret");
    String token = GoogleJwtCreator.build()
            .withPicture(PICTURE)
            .withEmail(EMAIL)
            .withIssuer("issuer")
            .withSubject("subject")
            .withAudience("audience")
            .withExp(expDate)
            .withIat(iat)
            .withName(NAME)
            .sign(algorithm);
    GoogleVerification verification = GoogleJWT.require(algorithm);
    JWT verifier = verification.createVerifierForGoogle(PICTURE, EMAIL, asList("issuer"), asList("audience"),
            NAME, 1, 1).build();
    DecodedJWT jwt = verifier.decode(token);
}
 
Example 7
Project: oma-riista-android   File: Utils.java   View Source Code Vote up 5 votes
static public Date parseDate(String dateString) {
    Date date = null;
    String[] formats = new String[]{DiaryDataSource.ISO_8601, DiaryDataSource.ISO_8601_SHORT};
    for (String format : formats) {
        SimpleDateFormat f = new SimpleDateFormat(format);
        try {
            date = f.parse(dateString);
            return date;
        } catch (ParseException ignored) {
        }
    }
    Calendar calendar = Calendar.getInstance();
    calendar.set(0, Calendar.JANUARY, 0);
    return calendar.getTime();
}
 
Example 8
Project: GongXianSheng   File: TimeUtils.java   View Source Code Vote up 5 votes
@SuppressLint("SimpleDateFormat")
public static String formatDate(String date) {
	SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat ft2 = new SimpleDateFormat("yyyy年MM月dd日");
	try {
		Date sDate = ft.parse(date);
		return ft2.format(sDate).toString();
	} catch (ParseException e) {
		return "";
	}
}
 
Example 9
Project: AssistantBySDK   File: TimeUtils.java   View Source Code Vote up 5 votes
public static Date parseDateTime(String dateTime) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
    try {
        return sdf.parse(dateTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 10
Project: sjk   File: DateString.java   View Source Code Vote up 5 votes
/**
 * 字符串转换成日期
 * 
 * @param str
 * @return date
 */
public static Date StrToDate(String str) {
    SimpleDateFormat format = new SimpleDateFormat(dateFormatter);
    Date date = null;
    try {
        date = format.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}
 
Example 11
Project: WeiXing_xmu-2016-MrCode   File: DateUtils.java   View Source Code Vote up 5 votes
/**
 * 获得当前格式化以后的时间(yyyy-MM-dd HH:mm:ss)
 * 
 * @param str
 * @param pattern
 * @return
 */
public static Date parseDate(String str, String pattern) {
	if (StringUtils.isEmpty(str)) {
		return null;
	}
	SimpleDateFormat format = new SimpleDateFormat(pattern);
	try {
		return format.parse(str);
	} catch (Exception e) {
		throw new RuntimeException("Could not parse date: "
				+ e.getMessage(), e);
	}
}
 
Example 12
Project: os   File: DateUtils.java   View Source Code Vote up 5 votes
/**
 * 时间串转化为Date
 * 
 * @param dateStr
 *            dateFormat时间格式的字符串
 * @param dateFormat
 *            时间格式
 * @return Date
 */
public static Date str2Date(String dateStr, String dateFormat) {
	if (ValidateHelper.isEmptyString(dateStr)) {
		return null;
	}

	SimpleDateFormat df = new SimpleDateFormat(dateFormat);
	try {
		return df.parse(dateStr);
	} catch (Exception ex) {
		return null;
	}
}
 
Example 13
Project: DateRangePickerLibrary   File: SampleTimesSquareActivity.java   View Source Code Vote up 5 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog_customized);

  final Calendar nextYear = Calendar.getInstance();
  nextYear.add(Calendar.YEAR, 1);

  final Calendar lastYear = Calendar.getInstance();
  lastYear.add(Calendar.YEAR, -1);

  calendar = (CalendarPickerView) findViewById(R.id.calendar_view);
  calendar.init(lastYear.getTime(), nextYear.getTime()) //
          .inMode(SelectionMode.RANGE) //
          .withSelectedDate(new Date());


    SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");
    String strdate = "16-06-2017";
    String strdate2 = "14-06-2017";

    try {
        Date newdate = dateformat.parse(strdate);
        Date newdate2 = dateformat.parse(strdate2);
        ArrayList<Date> arrayList = new ArrayList<>();
        arrayList.add(newdate);
        arrayList.add(newdate2);
        calendar.highlightDates(arrayList);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    ArrayList<Integer> list = new ArrayList<>();
    list.add(2);
    list.add(3);

    calendar.deactivateDates(list);

    //initButtonListeners(nextYear, lastYear);
}
 
Example 14
Project: pullstring-android   File: Response.java   View Source Code Vote up 4 votes
public Response(JSONObject json) {
    // status defaults to success
    mStatus = new Status();
    JSONObject error = json.optJSONObject(Keys.Error);
    if (error != null) {
        mStatus.setSuccess(false);
        mStatus.setErrorMessage(error.optString(Keys.Message, "Unknown Error"));
        mStatus.setStatusCode(error.optInt(Keys.Status, 500));
    }

    // top-level JSON properties
    mConversationId = json.optString(Keys.ConversationId);
    mParticipantId = json.optString(Keys.ParticipantId);
    mETag = json.optString(Keys.ETag);
    mAsrHypothesis = json.optString(Keys.AsrHypothesis);
    mEndpoint = json.optString(Keys.EndpointHeader);
    mTimedResponseInterval = json.optDouble(Keys.TimedResponseInterval, 0);

    // last modified
    String interval = json.optString(Keys.LastModified);
    if (!interval.isEmpty()) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
        try {
            mLastModified = dateFormat.parse(interval);
        } catch (ParseException e) {
            e.printStackTrace();
            mLastModified = null;
        }
    }

    // outputs
    mOutputs = new ArrayList<>();
    JSONArray outputs = json.optJSONArray(Keys.Outputs);
    if (outputs != null) {
        for (int i = 0; i < outputs.length(); i++) {
            JSONObject output = outputs.optJSONObject(i);
            if (output == null || !output.has(Keys.OutputType)) {
                continue;
            }

            String type = output.optString(Keys.OutputType);

            if (type.equals(OutputType.BEHAVIOR.toString())) {
                mOutputs.add(new BehaviorOutput(output));
            } else if (type.equals(OutputType.DIALOG.toString())) {
                mOutputs.add(new DialogOutput(output));
            }
        }
    }

    // entities -- convert from JSON dictionary to an array
    mEntities = new ArrayList<>();
    JSONObject entities = json.optJSONObject(Keys.Entities);
    if (entities != null) {
        Iterator<String> keys = entities.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object entity = entities.opt(key);

            if (entity == null) {
                continue;
            }

            if (entity instanceof String) {
                mEntities.add(new Label(key, (String)entity));
            } else if (entity instanceof JSONArray) {
                JSONArray arr = (JSONArray) entity;
                ArrayList<Object> list = new ArrayList<>();
                for (int i = 0; i < arr.length(); i++) {
                    Object item = arr.opt(i);
                    if (item != null) list.add(item);
                }
                mEntities.add(new List(key, list));
            } else if (entity instanceof Boolean) {
                mEntities.add(new Flag(key, (boolean)entity));
            } else if (entity instanceof Number) {
                mEntities.add(new Counter(key, ((Number)entity).doubleValue()));
            }
        }
    }
}
 
Example 15
Project: schulcloud-mobile-android   File: DaysBetweenUtilTest.java   View Source Code Vote up 4 votes
@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 16
Project: HutHelper   File: ExamAdapter.java   View Source Code Vote up 4 votes
@Override
public void onBindViewHolder(ExamViewHolder holder, int position) {
    Exam exam = examList.get(position);
    //坑,居然还会返回null
    if (!TextUtils.isEmpty(exam.getStarttime()) && !TextUtils.isEmpty(exam.getEndTime())) {
        String[] startTime = exam.getStarttime().split(" ");
        String[] endTime = exam.getEndTime().split(" ");

        holder.tvGradeLesson.setText(startTime[0]);
        holder.tvExamitemTime.setText(String.valueOf("(" + exam.getWeek_Num() + "周 "
                + startTime[1].substring(0, 5) + "-" + endTime[1].substring(0, 5) + ")"));

        String remainder = "今天";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            Date startDate = simpleDateFormat.parse(exam.getStarttime());
            Date endDate = simpleDateFormat.parse(exam.getEndTime());
            Date nowDate = new Date();

            long startHours = (startDate.getTime() - nowDate.getTime()) / (60 * 60 * 1000); //获得剩余小时
            long endHours = (endDate.getTime() - nowDate.getTime()) / (60 * 60 * 1000);

            if (startHours >= 24) {
                long day = startHours / 24;
                if (startHours % 24 > 0) {
                    day++;
                }
                remainder = "剩余" + day + "天";
            } else if (startHours > 0 && startHours < 24) {
                remainder = "剩余" + (startHours + 1) + "小时";
            } else if (startHours <= 0 && endHours > 0) {
                remainder = "正在进行";
            } else if (endHours <= 0) {
                remainder = "已结束";
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        holder.tvGradeScore.setText(remainder);
    } else {
        holder.tvGradeLesson.setText("未知");
        holder.tvGradeTime.setText("未知");
        holder.tvExamitemTime.setText(String.valueOf("(" + exam.getWeek_Num() + "周" + ")"));
        holder.tvGradeScore.setText("未知");
    }

    //isset不确定是不是重修标记
    // if (!exam.getIsset().equals("0")){
    //     holder.tvGradeTime.setText(String.valueOf(exam.getCourseName() + "(重修)"));
    // }else {
    //     holder.tvGradeTime.setText(exam.getCourseName());
    // }

    holder.tvGradeTime.setText(exam.getCourseName());

    String roomName = exam.getRoomName();
    holder.tvGradeJidian.setText(TextUtils.isEmpty(roomName) ? "未知" : roomName);

}
 
Example 17
Project: puremadrid   File: DataBaseLoader.java   View Source Code Vote up 4 votes
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

    ApiMedicion medicion = new ApiMedicion();

    while (cursor.moveToNext()){

        Compuesto compuesto = Compuesto.withName(cursor.getString(cursor.getColumnIndex(COLUMN_PARTICLE)));

        if (compuesto == Compuesto.NO2) {
            medicion.setAviso(cursor.getString(cursor.getColumnIndex(COLUMN_AVISO_LEVEL_NOW)));
            medicion.setAvisoMaxToday(cursor.getString(cursor.getColumnIndex(COLUMN_AVISO_MAX_LEVEL_TODAY)));
            medicion.setAvisoState(cursor.getString(cursor.getColumnIndex(COLUMN_AVISO_STATE)));
            medicion.setEscenarioManualTomorrow(cursor.getString(cursor.getColumnIndex(COLUMN_SCENARIO_MANUAL_TOMORROW)));
            medicion.setEscenarioStateTomorrow(cursor.getString(cursor.getColumnIndex(COLUMN_SCENARIO_TOMORROW)));
            medicion.setEscenarioStateToday(cursor.getString(cursor.getColumnIndex(COLUMN_SCENARIO_TODAY)));
        }
        // Date
        String dateString = cursor.getString(cursor.getColumnIndex(COLUMN_DATE));
        SimpleDateFormat formatter = new SimpleDateFormat(PureMadridDbHelper.databaseDateFormat);
        try {
            Date date = formatter.parse(dateString);
            medicion.setMeasuredAt(date.getTime());
        } catch (ParseException e) {

        }

        // Add stations
        JsonMap valuesMap = new JsonMap();
        Station[] stations = new Gson().fromJson(GlobalUtils.getString(GlobalUtils.getInputStream("stations.json")), Station[].class);
        for (Station station : stations){
            String stationId = COLUMN_BASE_STATION + String.format("%02d", station.getId());
            double value = cursor.getDouble(cursor.getColumnIndex(stationId));
            valuesMap.put(stationId,value);
        }

        switch (compuesto){
            case NO2: medicion.setNo2(valuesMap); break;
            case CO: medicion.setCoValues(valuesMap); break;
            case SO2: medicion.setSo2values(valuesMap); break;
            case O3: medicion.setO3values(valuesMap); break;
            case TOL: medicion.setTolValues(valuesMap); break;
            case BEN: medicion.setBenValues(valuesMap); break;
            case PM2_5: medicion.setPm25values(valuesMap); break;
            case PM10: medicion.setPm10values(valuesMap); break;
        }
    }
    mCallbacks.onDBFinished(medicion);
    cursor.close();
}
 
Example 18
Project: Toodoo   File: ToodooNote.java   View Source Code Vote up 4 votes
public Date timeStringToDate(String timeString) throws ParseException {
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a", Locale.US);

    Date newTime = simpleDateFormat.parse(timeString);
    return newTime;
}
 
Example 19
Project: SoaringCoach   File: FlightDate.java   View Source Code Vote up 4 votes
public String getFlightDateString() throws ParseException {
	SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat parse = new SimpleDateFormat("ddMMyy");
	Date date = parse.parse(ddmmyy);
	return output.format(date);
}
 
Example 20
Project: java-snippets   File: Library.java   View Source Code Vote up 2 votes
/**
 * Convert string to date
 * @param date the date string
 * @param format expected date format
 * @return Date
 * @throws ParseException
 */
public static Date stringToDate(String date, String format) throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
    return simpleDateFormat.parse(date);
}