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

The following examples show how to use java.text.SimpleDateFormat#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Util.java    From MFCalendarView with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 2
Source File: SimpleMMcifConsumer.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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);
}
 
Example 3
Source File: DatabaseHelper.java    From Paperwork-Android with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: CommonUtil.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: WorkUtils.java    From iceworkday with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: DateUtils.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
/**
 * 获取几天之后的日期(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;
}
 
Example 7
Source File: UserContextMapper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: DatesTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example 9
Source File: SubversionLogVTI.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * <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() ); }
}
 
Example 10
Source File: StringUtils.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: TaskQueryTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 12
Source File: DateKit.java    From Jantent with MIT License 5 votes vote down vote up
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;
}
 
Example 13
Source File: InputConfig.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
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;
	}
}
 
Example 14
Source File: TestMmcifV5Changes.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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());
}
 
Example 15
Source File: UtilAll.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static Date parseDate(String date, String pattern) {
    SimpleDateFormat df = new SimpleDateFormat(pattern);
    try {
        return df.parse(date);
    } catch (ParseException e) {
        return null;
    }
}
 
Example 16
Source File: DateUtils.java    From ToolsFinal with Apache License 2.0 5 votes vote down vote up
/**
 * 日期字符串转换为日期
 *
 * @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;
    }
}
 
Example 17
Source File: Date10ColumnCoder.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
protected Object decodeDateFromString(String v) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    try {
        return format.parse(v);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source File: UserSummary.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 19
Source File: SourceTargetComparer.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
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));
	// }
}
 
Example 20
Source File: HCalendarParser.java    From cosmo with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}