下面列出了java.text.SimpleDateFormat#parse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Converts date from a String to a Date
*
* @param dateStr Date in UTC TimeZone
* @return Date in Locale TimeZone
*/
public static Date getDateTime(String dateStr)
{
Date date = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
try
{
date = dateFormat.parse(dateStr);
}
catch (ParseException e)
{
Log.e(LOG_TAG, "Error parsing date: " + dateStr);
}
return date;
}
/**
* 获取几天之后的日期(wq)
*
* @param date yyyy-MM-dd HH:mm:ss
* @param day 加减的天数
* @return
*/
public static Date getDate(String date, int day) {
SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date beforeDate = formate.parse(date);
cal.setTime(beforeDate);
cal.add(Calendar.DAY_OF_MONTH, day);
//cal.set(beforeDate.getYear(), beforeDate.getMonth(), beforeDate.getDay()+day, beforeDate.getHours(),beforeDate.getSeconds(), beforeDate.getMinutes());
Date newDate = cal.getTime();
return newDate;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void newPdbxDatabaseStatus(PdbxDatabaseStatus status) {
// the deposition date field is only available in mmCIF 5.0
if (status.getRecvd_initial_deposition_date() == null) {
// skip this method for older mmCIF versions
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
PDBHeader header = structure.getPDBHeader();
if (header == null) {
header = new PDBHeader();
}
try {
Date depositionDate = dateFormat.parse(status.getRecvd_initial_deposition_date());
header.setDepDate(depositionDate);
} catch (ParseException e){
logger.warn("Could not parse date string '{}', deposition date will be unavailable", status.getRecvd_initial_deposition_date());
}
structure.setPDBHeader(header);
}
/**
* Herhangi bir tarih bilgisini Long'a çevirir
*
* @param date like 2013-12-17
* */
public static long dateToLong(String date){
SimpleDateFormat formatter =
new SimpleDateFormat("yyyy-MM-dd", new Locale("TR"));
Date d = null;
try {
d = formatter.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(d);
return c.getTimeInMillis();
}
public static Date getYesterday() {
Date date = new Date();
long time = date.getTime() / 1000L - 86400L;
date.setTime(time * 1000L);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = format.parse(format.format(date));
} catch (Exception var5) {
System.out.println(var5.getMessage());
}
return date;
}
protected Object decodeDateFromString(String v) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(v);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 日期字符串转换为日期
*
* @param date 日期字符串
* @param pattern 格式
* @return 日期
*/
public static Date formatStringByFormat(String date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static Date parseDate(String date, String pattern) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
try {
return df.parse(date);
} catch (ParseException e) {
return null;
}
}
@Test
public void testReleaseDate() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
Date releaseDate = dateFormat.parse("1992-10-15");
assertEquals(releaseDate, s.getPDBHeader().getRelDate());
}
public static boolean isTime(String strDate) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
boolean dateFlag = true;
try {
format.parse(strDate);
} catch (ParseException e) {
dateFlag = false;
}
return dateFlag;
}
private static int getWeekDay(String ymd) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = null;
try {
date = sdf.parse(ymd);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return day;
}
public String displayCreationDate() {
try {
SimpleDateFormat formater = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
Date date = formater.parse(creationDate);
return Utils.displayTime(date);
} catch (Exception exception) {
return creationDate;
}
}
private Date ldapStringToDate(String dateString) {
if (dateString != null) {
SimpleDateFormat test = new SimpleDateFormat("yyyyMMddHHmmss");
try {
return test.parse(dateString);
} catch (ParseException e) {
LOG.error("failed parsing ldap string to date {}", e);
}
}
return null;
}
public void testQueryCreatedOn() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
// Exact matching of createTime, should result in 6 tasks
Date createTime = sdf.parse("01/01/2001 01:01:01.000");
TaskQuery query = taskService.createTaskQuery().taskCreatedOn(createTime);
assertEquals(6, query.count());
assertEquals(6, query.list().size());
}
public static long dateTimeDifferenceHour(String format, String date1,
String date2) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d1 = sdf.parse(date1);
Date d2 = sdf.parse(date2);
long l = d1.getTime() - d2.getTime();
long hour = (l / (HOUR_OF_DAY * MINUTE_OF_HOUR * MILLION_SECOND_OF_SECOND));
return hour;
}
/**
* <p>
* Subversion formats timestamps thusly: "2007-09-16 11:17:37 -0700 (Sun, 16 Sep 2007)"
* </p>
*/
public java.sql.Timestamp getTimestamp(int columnIndex) throws SQLException
{
String columnValue = getString( columnIndex ).trim();
try {
SimpleDateFormat dateFormatter = getDateFormatter();
java.util.Date rawDate = dateFormatter.parse( columnValue );
long time = rawDate.getTime();
return new java.sql.Timestamp( time );
} catch (Throwable t) { throw new SQLException( t.getMessage() ); }
}
@Test
public void 指定した日付からlongで表される時間が取得できるかどうか() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date d = sdf.parse("2011/11/11");
assertThat(Dates.getTime(2011, 11, 11), is(d.getTime()));
}
/**
* Ical date.
* @param original The original.
* @return The date.
* @throws ParseException - if something is wrong this exception is thrown.
*/
private Date icalDate(String original)
throws ParseException {
// in the real world, some generators use iCalendar formatted
// dates and date-times, so try parsing those formats first before
// going to RFC 3339 formats
if (original.indexOf('T') == -1) {
// date-only
try {
// for some reason Date's pattern matches yyyy-MM-dd, so
// don't check it if we find -
if (original.indexOf('-') == -1) {
return new Date(original);
}
} catch (Exception e) {
LOG.warn("", e);
}
//The methods parse() and format() in java.text.Format contain a design flaw
//that can cause one user to see another user's data.
//moprea: making the object local will avoid thread safety issues
SimpleDateFormat hcalDateFormat =
new SimpleDateFormat(HCAL_DATE_PATTERN);
return new Date(hcalDateFormat.parse(original));
}
// Return DateTime if we don't find '-'
if(original.indexOf('-') == -1) {
return new DateTime(original);
}
// otherwise try parsing RFC 3339 formats
// the date-time value can represent its time zone in a few different
// ways. we have to normalize those to match our pattern.
String normalized = null;
if (LOG.isDebugEnabled()) {
LOG.debug("normalizing date-time " + original);
}
// 2002-10-09T19:00:00Z
if (original.charAt(original.length()-1) == 'Z') {
normalized = original.replace("Z", "GMT-00:00");
}
// 2002-10-10T00:00:00+05:00
else if (original.indexOf("GMT") == -1 &&
(original.charAt(original.length()-6) == '+' ||
original.charAt(original.length()-6) == '-')) {
String tzId = "GMT" + original.substring(original.length()-6);
normalized = original.substring(0, original.length()-6) + tzId;
}
else {
// 2002-10-10T00:00:00GMT+05:00
normalized = original;
}
//The methods parse() and format() in java.text.Format contain a design flaw
//that can cause one user to see another user's data.
//moprea: making the object local will avoid thread safety issues
SimpleDateFormat hcalDateTimeFormat = new SimpleDateFormat(HCAL_DATE_TIME_PATTERN);
DateTime dt = new DateTime(hcalDateTimeFormat.parse(normalized));
// hCalendar does not specify a representation for timezone ids
// or any other sort of timezone information. the best it does is
// give us a timezone offset that we can use to convert the local
// time to UTC. furthermore, it has no representation for floating
// date-times. therefore, all dates are converted to UTC.
dt.setUtc(true);
return dt;
}
/**
* Construct a UserSummary from the passed-in map and summaryOnly values.
* The map must have been returned from the Perforce server in response
* to a getUsers() or getUser (etc.) call; is summaryOnly is true, this
* is treated as a map that came from the getUseres method.<p>
*
* If map is null, this is equivalent to calling the default constructor.
*/
public UserSummary(Map<String, Object> map, boolean summaryOnly) {
super(!summaryOnly, !summaryOnly);
if (map != null) {
try{
this.loginName = (String) map.get("User");
this.email = (String) map.get("Email");
this.fullName = (String) map.get("FullName");
if (map.containsKey(MapKeys.TYPE_KEY)) {
this.type = UserType.fromString(((String) map.get(MapKeys.TYPE_KEY)).toUpperCase());
}
if (summaryOnly) {
this.update = new Date(Long.parseLong((String) map
.get(MapKeys.UPDATE_KEY)) * 1000);
this.access = new Date(Long.parseLong((String) map
.get(MapKeys.ACCESS_KEY)) * 1000);
if (map.get(MapKeys.TICKET_EXPIRATION) != null) {
this.ticketExpiration = new Date(Long.parseLong((String) map
.get(MapKeys.TICKET_EXPIRATION)) * 1000);
}
if (map.get(MapKeys.PASSWORD_CHANGE_KEY) != null) {
this.passwordChange = new Date(Long.parseLong((String) map
.get(MapKeys.PASSWORD_CHANGE_KEY)) * 1000);
}
} else {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
if (map.containsKey(MapKeys.UPDATE_KEY)) {
this.update = simpleDateFormat
.parse((String) map.get(MapKeys.UPDATE_KEY));
}
if (map.containsKey(MapKeys.ACCESS_KEY)) {
this.access = simpleDateFormat
.parse((String) map.get(MapKeys.ACCESS_KEY));
}
if (map.get(MapKeys.PASSWORD_CHANGE_LC_KEY) != null) {
this.passwordChange = simpleDateFormat
.parse((String) map.get(MapKeys.PASSWORD_CHANGE_LC_KEY));
}
}
} catch (Throwable thr) {
Log.error("Unexpected exception in UserSummary constructor: "
+ thr.getLocalizedMessage());
Log.exception(thr);
}
}
}
public static void main(String[] args) {
// String str1 = "11wfw21dwq33dqwaa44";
// String str2 = "11 bbwd22qwds21gre33";
// System.out.println(replaceNumber(str1, str2));
/** Part.1 使用正则表达式 **/
// String regx = "\\d{4}\\-\\d{1,2}\\-\\d{1,2}\\s\\d{1,2}\\:\\d{1,2}\\:\\d{1,2}";
// Pattern p = Pattern.compile(regx);
// Matcher m = p.matcher("你好 - 2008-8-7 12:04:11 - 中国2010-11-11 11:52:30 dwqdqw");
// while (m.find()) {
// System.out.println(m.group());
// }
/** Part.2 使用 java.text.SimpleDateFormat.parse(String text, ParsePosition pos) 方法 **/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = "form: 2008-8-7 12:04:11 to 2010-11-11 11:52:30, over!";
ParsePosition pos;
for (int i = 0; i < str.length();) {
pos = new ParsePosition(i);
int start = i;
Date date = sdf.parse(str, pos);
if (date != null) {
i = pos.getIndex();
System.out.println(str.substring(start, i).trim());
} else {
i++;
}
}
/** Part.3 使用“()”为正则表达式添加分组 **/
// Pattern p=Pattern.compile("(\\d{4})-(\\d{1,2})-(\\d{1,2})");
// Matcher m=p.matcher("x20xxx1984-10-20xxx19852x");
//
// if(m.find()){
// System.out.println("日期:"+m.group());
// System.out.println("年:"+m.group(1));
// System.out.println("月:"+m.group(2));
// System.out.println("日:"+m.group(3));
// }
}