Java Code Examples for java.text.SimpleDateFormat

The following are top voted examples for showing how to use java.text.SimpleDateFormat. 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 product more good examples.

Example 1
Project: jdroid   File: DateUtils.java View source code 7 votes vote down vote up
/**
 * @param dateFormatted The formatted string to parse
 * @param dateFormat
 * @return A date that represents the formatted string
 */
public static Date parse(String dateFormatted, SimpleDateFormat dateFormat) {
	Date date = null;
	if (StringUtils.isNotEmpty(dateFormatted)) {
		try {
			date = dateFormat.parse(dateFormatted);
		} catch (ParseException e) {
			throw new UnexpectedException("Error parsing the date: '" + dateFormatted + "' with pattern: "
					+ dateFormat.toPattern(), e);
		}
	}
	return date;
}
 
Example 2
Project: Magnolia   File: DateUtil.java View source code 7 votes vote down vote up
public static String format(Date date, String formatPattern, Locale locale) {
    if(date == null){
        return StringUtils.EMPTY;
    }

    if (formatPattern == null) {
        formatPattern = FORMAT_DEFAULTPATTERN;
    }

    if(FORMAT_DATE_SHORT.equals(formatPattern)){
        return SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale).format(date);
    }
    else if (FORMAT_DATE_MEDIUM.equals(formatPattern)){
        return SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, locale).format(date);
    }
    else if (FORMAT_DATE_LONG.equals(formatPattern)){
        return SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, locale).format(date);
    }
    else if (FORMAT_TIME_SHORT.equals(formatPattern)){
        return SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT,locale).format(date);
    }
    else if (FORMAT_TIME_MEDIUM.equals(formatPattern)){
        return SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM,locale).format(date);
    }
    else if (FORMAT_TIME_LONG.equals(formatPattern)){
        return SimpleDateFormat.getTimeInstance(SimpleDateFormat.LONG,locale).format(date);
    }
    else if (FORMAT_DATETIME_SHORT.equals(formatPattern)){
        return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT,SimpleDateFormat.SHORT,locale).format(date);
    }
    else if (FORMAT_DATETIME_MEDIUM.equals(formatPattern)){
        return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale).format(date);
    }
    else if (FORMAT_DATETIME_LONG.equals(formatPattern)){
        return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG, locale).format(date);
    }
    else {
        return DateFormatUtils.format(date, formatPattern, locale);
    }
}
 
Example 3
Project: jeboorker   File: DateConversionUtils.java View source code 7 votes vote down vote up
public Date getDate(String dateString) {
	SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
	format.setDateFormatSymbols(new DateFormatSymbols(Locale.US));
	try {
		return format.parse(dateString);
	} catch (ParseException e) {
		throw new RuntimeException("could not parse date " + dateString);
	}
}
 
Example 4
Project: sslcertx   File: ParameterWriter.java View source code 6 votes vote down vote up
public static void writeDate(OutputStream out, java.util.Date date, Calendar calendar) throws IOException {
   out.write(QUOTE);
   String dateString;
   if (calendar != null) {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       sdf.setCalendar(calendar);
       dateString = sdf.format(date);
   } else {
       dateString = date.toString();
   }
   out.write(dateString.getBytes());
   out.write(QUOTE);
}
 
Example 5
Project: sslcertx   File: AbstractValueObject.java View source code 6 votes vote down vote up
public Date getDate() throws ParseException {
    if (rawBytes == null) {
        return null;
    }

    String rawValue = getString();
    SimpleDateFormat sdf;
    if (dataType.getType() == MySQLType.Type.YEAR) {
       if (rawBytes.length == 2) {
          sdf = new SimpleDateFormat("yy");
       } else {
          sdf = new SimpleDateFormat("yyyy");
       }
    } else {
        sdf = new SimpleDateFormat("yyyy-MM-dd");
    }
    java.util.Date utilDate = sdf.parse(rawValue);
    return new Date(utilDate.getTime());
}
 
Example 6
Project: my-ministry-assistant   File: TimeUtils.java View source code 6 votes vote down vote up
public static Date parseTimestamp(String timestamp) {
    for (SimpleDateFormat format : ACCEPTED_TIMESTAMP_FORMATS) {
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        try {
            return format.parse(timestamp);
        } catch (ParseException ex) {
            continue;
        }
    }

    // All attempts to parse have failed
    return null;
}
 
Example 7
Project: sslcertx   File: AbstractValueObject.java View source code 6 votes vote down vote up
public Timestamp getTimestamp() throws ParseException {
    if (rawBytes == null) {
        return null;
    }
    String rawValue = getString();
    SimpleDateFormat sdf;

    if (rawValue.length() > 11) {
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    } else {
        sdf = new SimpleDateFormat("yyyy-MM-dd");
    }
    sdf.setLenient(false);
    final java.util.Date utilTime = sdf.parse(rawValue);
    Timestamp ts = new Timestamp(utilTime.getTime());
    if(rawValue.indexOf('.') != -1) {
        ts.setNanos(extractNanos(rawValue));
    }
    return ts;
}
 
Example 8
Project: sslcertx   File: AbstractValueObject.java View source code 6 votes vote down vote up
public Date getDate(final Calendar cal) throws ParseException {
    if (rawBytes == null) {
        return null;
    }
    final String rawValue = getString();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setCalendar(cal);
    final java.util.Date utilDate = sdf.parse(rawValue);
    return new Date(utilDate.getTime());
}
 
Example 9
Project: externals   File: DateFormatManager.java View source code 6 votes vote down vote up
public String format(Date date, String pattern) {
  DateFormat formatter = null;
  formatter = getDateFormatInstance();
  if (formatter instanceof SimpleDateFormat) {
    formatter = (SimpleDateFormat) (formatter.clone());
    ((SimpleDateFormat) formatter).applyPattern(pattern);
  }
  return formatter.format(date);
}
 
Example 10
Project: ngCordova-demo   File: Globalization.java View source code 6 votes vote down vote up
private JSONObject getDatePattern(JSONArray options) throws GlobalizationError{
    JSONObject obj = new JSONObject();

    try{
        SimpleDateFormat fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getDateFormat(this.cordova.getActivity()); //default user preference for date
        SimpleDateFormat fmtTime = (SimpleDateFormat)android.text.format.DateFormat.getTimeFormat(this.cordova.getActivity());  //default user preference for time

        String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a

        //get Date value + options (if available)
        if (options.getJSONObject(0).has(OPTIONS)){
            //options were included

            JSONObject innerOptions = options.getJSONObject(0).getJSONObject(OPTIONS);
            //get formatLength option
            if (!innerOptions.isNull(FORMATLENGTH)){
                String fmtOpt = innerOptions.getString(FORMATLENGTH);
                if (fmtOpt.equalsIgnoreCase(MEDIUM)){//medium
                    fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getMediumDateFormat(this.cordova.getActivity());
                }else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)){ //long/full
                    fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getLongDateFormat(this.cordova.getActivity());
                }
            }

            //return pattern type
            fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern();
            if (!innerOptions.isNull(SELECTOR)){
                String selOpt = innerOptions.getString(SELECTOR);
                if (selOpt.equalsIgnoreCase(DATE)){
                    fmt =  fmtDate.toLocalizedPattern();
                }else if (selOpt.equalsIgnoreCase(TIME)){
                    fmt = fmtTime.toLocalizedPattern();
                }
            }
        }

        //TimeZone from users device
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());

        obj.put("pattern", fmt);
        obj.put("timezone", tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()),TimeZone.SHORT));
        obj.put("utc_offset", tz.getRawOffset()/1000);
        obj.put("dst_offset", tz.getDSTSavings()/1000);
        return obj;

    }catch(Exception ge){
        throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
    }
}
 
Example 11
Project: Klyph   File: DateUtil.java View source code 6 votes vote down vote up
private static SimpleDateFormat getDateFormat()
{
	SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL);
	String pattern = dateFormat.toLocalizedPattern();

	pattern = pattern.replace("y", "");
	pattern = pattern.replace("E", "");
	pattern = pattern.replace(",", "");
	pattern = pattern.replace("  ", " ");
	pattern = pattern.trim();

	dateFormat.applyLocalizedPattern(pattern);

	return dateFormat;
}
 
Example 12
Project: WebQQCore   File: QQHttpCookie.java View source code 6 votes vote down vote up
/**
   * ???????cookie?????cookie
   * @param cookie
   */
  public QQHttpCookie(String cookie)
  {
  	/*
  	?????name, value, domain, path, Max-Age(expired)
  	The syntax for the Set-Cookie response header is

  	   set-cookie      =       "Set-Cookie:" cookies
  	   cookies         =       1#cookie
  	   cookie          =       NAME "=" VALUE *(";" cookie-av)
  	   NAME            =       attr
  	   VALUE           =       value
  	   cookie-av       =       "Comment" "=" value
  	                   |       "Domain" "=" value
  	                   |       "Max-Age" "=" value
  	                   |       "Path" "=" value
  	                   |       "Secure"
  	                   |       "Version" "=" 1*DIGIT
*/
  	String[] parts = cookie.split(";");
  	if(parts.length<2)	throw new IllegalArgumentException("Invalid cookie string:"+cookie);
  	
  	for(int i=0; i<parts.length; i++) {
  		String[] pairs = parts[i].split("=");
  		String key = pairs[0].trim();
  		String val = pairs.length>1 ? pairs[1].trim() : "";
  		if(i==0) {	//??name?value
  			this.name = key;
  			this.value = val;
  		}else {
  			key = key.toLowerCase();
  			if(key.equals("domain")) {
  				this.domain = val;
  			}else if(key.equals("max-age")) {
  				try {
                   this.expired = SimpleDateFormat.getInstance().parse(val);
                  } catch (ParseException e) {
                  	throw new IllegalArgumentException("parse exipred failed.", e);
                  }
  			}else if(key.equals("path")) {
  				this.path = val;
  			}
  		}
  	}

  }
 
Example 13
Project: open-mika   File: SimpleDateFormatTest.java View source code 6 votes vote down vote up
/**
 * @tests java.text.SimpleDateFormat#getDateFormatSymbols()
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "",
    method = "getDateFormatSymbols",
    args = {}
)
 */
public void test_getDateFormatSymbols() {
    // Test for method java.text.DateFormatSymbols
    // java.text.SimpleDateFormat.getDateFormatSymbols()
    SimpleDateFormat df = (SimpleDateFormat) DateFormat.getInstance();
    DateFormatSymbols dfs = df.getDateFormatSymbols();
    assertTrue("Symbols identical", dfs != df.getDateFormatSymbols());
}
 
Example 14
Project: jeboorker   File: DateUtils.java View source code 6 votes vote down vote up
/**
 * The given value will be added to the specified interval of the date
 * 
 * @param interval
 *            The part of the date which has to be added:
 *            <li>"yyyy" for year</li>
 *            <li>"m" for month</li>
 *            <li>"q" for quarter</li>
 *            <li>"d" for day</li>
 *            <li>"w" for weekday</li>
 *            <li>"ww" for week of Year</li>
 *            <li>"y" for day of year</li>
 *            <li>"h" for hour</li>
 *            <li>"m" for minute</li>
 *            <li>"s" for second</li>
 * 
 * <pre>
 * In this method, &quot;d&quot;,&quot;w&quot; and &quot;y&quot; are the same,
 * they only add one day to the date,
 * &quot;ww&quot; adds one full week(7 days).
 * </pre>
 * 
 * @param value
 *            The value which has to be added to the interval
 * @param date
 *            The date which will be changed
 * @return The changed date
 */
public static Date dateAdd(final String interval, final int value, final Date date) {
	SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss");
	dateFormat.format(date);
	Calendar calendar = dateFormat.getCalendar();
	if (interval.equals("yyyy")) {
		calendar.add(Calendar.YEAR, value);
	} else if (interval.equals("m")) {
		calendar.add(Calendar.MONTH, value);
	} else if (interval.equals("q")) {
		calendar.add(Calendar.MONTH, value * UtilConstants.MULTIPLICATION_TO_QUARTER);
	} else if (interval.equals("d") || interval.equals("w") || interval.equals("y")) {
		calendar.add(Calendar.DAY_OF_MONTH, value);
	} else if (interval.equals("ww")) {
		calendar.add(Calendar.WEEK_OF_YEAR, value);
	} else if (interval.equals("h")) {
		calendar.add(Calendar.HOUR, value);
	} else if (interval.equals("n")) {
		calendar.add(Calendar.MINUTE, value);
	} else if (interval.equals("s")) {
		calendar.add(Calendar.SECOND, value);
	}

	return calendar.getTime();
}
 
Example 15
Project: SOLR   File: DateUtil.java View source code 5 votes vote down vote up
/**
 * Slightly modified from org.apache.commons.httpclient.util.DateUtil.parseDate
 * <p/>
 * Parses the date value using the given date formats.
 *
 * @param dateValue   the date value to parse
 * @param dateFormats the date formats to use
 * @param startDate   During parsing, two digit years will be placed in the range
 *                    <code>startDate</code> to <code>startDate + 100 years</code>. This value may
 *                    be <code>null</code>. When <code>null</code> is given as a parameter, year
 *                    <code>2000</code> will be used.
 * @return the parsed date
 * @throws ParseException if none of the dataFormats could parse the dateValue
 */
public static Date parseDate(
        String dateValue,
        Collection<String> dateFormats,
        Date startDate
) throws ParseException {

  if (dateValue == null) {
    throw new IllegalArgumentException("dateValue is null");
  }
  if (dateFormats == null) {
    dateFormats = DEFAULT_HTTP_CLIENT_PATTERNS;
  }
  if (startDate == null) {
    startDate = DEFAULT_TWO_DIGIT_YEAR_START;
  }
  // trim single quotes around date if present
  // see issue #5279
  if (dateValue.length() > 1
          && dateValue.startsWith("'")
          && dateValue.endsWith("'")
          ) {
    dateValue = dateValue.substring(1, dateValue.length() - 1);
  }

  SimpleDateFormat dateParser = null;
  Iterator formatIter = dateFormats.iterator();

  while (formatIter.hasNext()) {
    String format = (String) formatIter.next();
    if (dateParser == null) {
      dateParser = new SimpleDateFormat(format, Locale.US);
      dateParser.setTimeZone(GMT);
      dateParser.set2DigitYearStart(startDate);
    } else {
      dateParser.applyPattern(format);
    }
    try {
      return dateParser.parse(dateValue);
    } catch (ParseException pe) {
      // ignore this exception, we will try the next format
    }
  }

  // we were unable to parse the date
  throw new ParseException("Unable to parse the date " + dateValue, 0);
}
 
Example 16
Project: queueing-simulation   File: MonthDateFormat.java View source code 5 votes vote down vote up
/**
 * Some test code.
 *
 * @param args  ignored.
 */
public static void main(String[] args) {
    MonthDateFormat mdf = new MonthDateFormat(Locale.UK, 2);
    System.out.println("UK:");
    System.out.println(mdf.format(new Month(1, 2005).getStart()));
    System.out.println(mdf.format(new Month(2, 2005).getStart()));
    System.out.println(mdf.format(new Month(3, 2005).getStart()));
    System.out.println(mdf.format(new Month(4, 2005).getStart()));
    System.out.println(mdf.format(new Month(5, 2005).getStart()));
    System.out.println(mdf.format(new Month(6, 2005).getStart()));
    System.out.println(mdf.format(new Month(7, 2005).getStart()));
    System.out.println(mdf.format(new Month(8, 2005).getStart()));
    System.out.println(mdf.format(new Month(9, 2005).getStart()));
    System.out.println(mdf.format(new Month(10, 2005).getStart()));
    System.out.println(mdf.format(new Month(11, 2005).getStart()));
    System.out.println(mdf.format(new Month(12, 2005).getStart()));
    System.out.println();

    mdf = new MonthDateFormat(Locale.GERMANY, 2);
    System.out.println("GERMANY:");
    System.out.println(mdf.format(new Month(1, 2005).getStart()));
    System.out.println(mdf.format(new Month(2, 2005).getStart()));
    System.out.println(mdf.format(new Month(3, 2005).getStart()));
    System.out.println(mdf.format(new Month(4, 2005).getStart()));
    System.out.println(mdf.format(new Month(5, 2005).getStart()));
    System.out.println(mdf.format(new Month(6, 2005).getStart()));
    System.out.println(mdf.format(new Month(7, 2005).getStart()));
    System.out.println(mdf.format(new Month(8, 2005).getStart()));
    System.out.println(mdf.format(new Month(9, 2005).getStart()));
    System.out.println(mdf.format(new Month(10, 2005).getStart()));
    System.out.println(mdf.format(new Month(11, 2005).getStart()));
    System.out.println(mdf.format(new Month(12, 2005).getStart()));
    System.out.println();

    mdf = new MonthDateFormat(Locale.FRANCE, 2);
    System.out.println("FRANCE:");
    System.out.println(mdf.format(new Month(1, 2005).getStart()));
    System.out.println(mdf.format(new Month(2, 2005).getStart()));
    System.out.println(mdf.format(new Month(3, 2005).getStart()));
    System.out.println(mdf.format(new Month(4, 2005).getStart()));
    System.out.println(mdf.format(new Month(5, 2005).getStart()));
    System.out.println(mdf.format(new Month(6, 2005).getStart()));
    System.out.println(mdf.format(new Month(7, 2005).getStart()));
    System.out.println(mdf.format(new Month(8, 2005).getStart()));
    System.out.println(mdf.format(new Month(9, 2005).getStart()));
    System.out.println(mdf.format(new Month(10, 2005).getStart()));
    System.out.println(mdf.format(new Month(11, 2005).getStart()));
    System.out.println(mdf.format(new Month(12, 2005).getStart()));
    System.out.println();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    sdf.setNumberFormat(null);
}