Java Code Examples for java.text.DateFormat

The following are top voted examples for showing how to use java.text.DateFormat. 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: my-ministry-assistant   File: TimeUtils.java View source code 6 votes vote down vote up
public static String formatShortTime(Context context, Date time) {
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
    TimeZone tz = PrefUtils.getDisplayTimeZone(context);
    if (tz != null) {
        format.setTimeZone(tz);
    }
    return format.format(time);
}
 
Example 2
Project: lucene-addons   File: QueryParserTestCase.java View source code 6 votes vote down vote up
/**
 * formats the given year+month+day as a localized date in the gregorian calendar
 */
protected String getLocalizedDate(int year, int month, int day) {
  // we use the default Locale/TZ since LuceneTestCase randomizes it
  DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
  Calendar calendar = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
  calendar.clear();
  calendar.set(year, month, day);
  calendar.set(Calendar.HOUR_OF_DAY, 23);
  calendar.set(Calendar.MINUTE, 59);
  calendar.set(Calendar.SECOND, 59);
  calendar.set(Calendar.MILLISECOND, 999);
  return df.format(calendar.getTime());
}
 
Example 3
Project: breakout   File: I18n.java View source code 6 votes vote down vote up
public static Binder<String> formattedDateTimeBinder( Binder<Date> dateBinder , int dateStyle , int timeStyle )
{
	Binder<DateFormat> formatBinder = new FunctionBinder<>( localeBinderHolder ,
		locale -> locale == null ? DateFormat.getDateTimeInstance( dateStyle , timeStyle ) :
			DateFormat.getDateTimeInstance( dateStyle , timeStyle , locale ) );

	return new BiFunctionBinder<>( dateBinder , formatBinder ,
		( date , format ) -> date == null || format == null ? null : format.format( date ) );
}
 
Example 4
Project: richfaces   File: ChatBean.java View source code 6 votes vote down vote up
@Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
    try {
        Message messageObject = new Message(message, sender, DateFormat.getInstance().format(new Date()));
        getTopicsContext().publish(new TopicKey("chat", getMessagesSubtopic()), messageObject);
    } catch (MessageException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example 5
Project: OurApp   File: AddressBookResultHandler.java View source code 6 votes vote down vote up
private static Date parseDate(String s) {
  for (DateFormat currentFomat : DATE_FORMATS) {
    synchronized (currentFomat) {
      currentFomat.setLenient(false);
      Date result = currentFomat.parse(s, new ParsePosition(0));
      if (result != null) {
        return result;
      }
    }
  }
  return null;
}
 
Example 6
Project: JerseyTest   File: CustomerResource.java View source code 6 votes vote down vote up
@POST
@Produces("text/html")
public Response createCustomer(@FormParam("firstname") String first,
                               @FormParam("lastname") String last)
{
   Customer customer = new Customer();
   customer.setId(idCounter.incrementAndGet());
   customer.setFirstName(first);
   customer.setLastName(last);
   customerDB.put(customer.getId(), customer);
   System.out.println("Created customer " + customer.getId());
   String output = "Created customer <a href=\"customers/" + customer.getId() + "\">" + customer.getId() + "</a>";
   String lastVisit = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date());
   URI location = URI.create("/customers/" + customer.getId());
   return Response.created(location)
           .entity(output)
           .cookie(new NewCookie("last-visit", lastVisit))
           .build();

}
 
Example 7
Project: wicketstuff-security   File: SwarmMockHttpServletRequest.java View source code 6 votes vote down vote up
/**
 * Get the given header as a date.
 * 
 * @param name
 *            The header name
 * @return The date, or -1 if header not found
 * @throws IllegalArgumentException
 *             If the header cannot be converted
 */
public long getDateHeader(final String name) throws IllegalArgumentException
{
	String value = getHeader(name);
	if (value == null)
	{
		return -1;
	}

	DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
	try
	{
		return df.parse(value).getTime();
	}
	catch (ParseException e)
	{
		throw new IllegalArgumentException("Can't convert header to date " + name + ": "
			+ value);
	}
}
 
Example 8
Project: appstatus   File: HtmlUtils.java View source code 6 votes vote down vote up
/**
 * Outputs one table row
 * 
 * @param os
 * @param status
 * @param cols
 * @throws IOException
 */
public static void generateRow(StrBuilder sb, String status, Object... cols) throws IOException {
	sb.append("<tr>");

	sb.append(("<td class='icon'><img src='?icon=" + status + "'></td>"));

	for (Object obj : cols) {
		sb.append("<td>");
		if (obj != null) {

			if (obj instanceof Date) {
				DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
				sb.append(dateFormat.format((Date) obj));
			} else {
				sb.append(obj.toString());
			}
		}
		sb.append("</td>");

	}
	sb.append("</tr>");
}
 
Example 9
Project: queueing-simulation   File: TimeSeriesURLGenerator.java View source code 6 votes vote down vote up
/**
 * Construct TimeSeriesURLGenerator overriding defaults.
 *
 * @param dateFormat  a formatter for the date (<code>null</code> not
 *         permitted).
 * @param prefix  the prefix of the URL (<code>null</code> not permitted).
 * @param seriesParameterName  the name of the series parameter in the URL
 *         (<code>null</code> not permitted).
 * @param itemParameterName  the name of the item parameter in the URL
 *         (<code>null</code> not permitted).
 */
public TimeSeriesURLGenerator(DateFormat dateFormat, String prefix,
        String seriesParameterName, String itemParameterName) {

    if (dateFormat == null) {
        throw new IllegalArgumentException("Null 'dateFormat' argument.");
    }
    if (prefix == null) {
        throw new IllegalArgumentException("Null 'prefix' argument.");
    }
    if (seriesParameterName == null) {
        throw new IllegalArgumentException(
                "Null 'seriesParameterName' argument.");
    }
    if (itemParameterName == null) {
        throw new IllegalArgumentException(
                "Null 'itemParameterName' argument.");
    }

    this.dateFormat = (DateFormat) dateFormat.clone();
    this.prefix = prefix;
    this.seriesParameterName = seriesParameterName;
    this.itemParameterName = itemParameterName;

}
 
Example 10
Project: jamppa   File: StringUtils.java View source code 6 votes vote down vote up
private static Calendar parseXEP91Date(String stampString,
        DateFormat dateFormat) {
    try {
        synchronized (dateFormat) {
            dateFormat.parse(stampString);
            return dateFormat.getCalendar();
        }
    } catch (ParseException e) {
        return null;
    }
}
 
Example 11
Project: pentaho-metadata-editor   File: LegacyLocalizationUtilTest.java View source code 6 votes vote down vote up
public void buildLargeXmi() throws Exception {
  XmiParser parser = new XmiParser();
  Domain domain = parser.parseXmi(new FileInputStream("/temp/metadata.xmi"));
  
  LocalizationUtil util = new LocalizationUtil();
  
  String locale = "en-US";
  Properties enUs = util.exportLocalizedProperties(domain, locale);
  
  Properties temp = null;
  
  Locale[] locales = DateFormat.getAvailableLocales();
  
  for(int i = 0; i < locales.length; i++) {
    temp = new Properties();
    for(Object key : enUs.keySet()) {
      temp.put(key, "[" + locales[i].toString() + "] " + enUs.get(key).toString());
    }
    util.importLocalizedProperties(domain, temp, locales[i].toString().replace("_","-"));
  }
  
  new FileOutputStream("/temp/multi-locale.xmi").write(parser.generateXmi(domain).getBytes("UTF-8"));
}
 
Example 12
Project: Time4J   File: ChronoFormatter.java View source code 6 votes vote down vote up
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object o) {

    String calendarType =
        this.formatter.globalAttributes.get(Attributes.CALENDAR_TYPE, ISO_CALENDAR_TYPE);

    if (calendarType.equals(ISO_CALENDAR_TYPE)) {
        try {
            StringBuilder toAppendTo = new StringBuilder();
            T formattable =
                this.formatter.getChronology().getChronoType().cast(o);
            Set<ElementPosition> positions =
                this.formatter.print(formattable, toAppendTo);
            AttributedString as =
                new AttributedString(toAppendTo.toString());
            for (ElementPosition position : positions) {
                DateFormat.Field field = toField(position.getElement());
                if (field != null) {
                    as.addAttribute(
                        field,
                        field,
                        position.getStartIndex(),
                        position.getEndIndex());
                }
            }
            return as.getIterator();
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(
                "Not formattable: " + o, cce);
        }
    }

    return super.formatToCharacterIterator(o);

}
 
Example 13
Project: ArubaSyslog   File: SessionExtraction.java View source code 5 votes vote down vote up
private static List<String> extractRoughSessions(List<String> allLines) throws ParseException {
    List<String> roughSessions = new LinkedList<String>();
    //prepare to store the "Auth" log, K: ap name , V: date_string
    TreeMap<String, String> ap_auth_tmap = new TreeMap<String, String>();                   
    //start exacting the movement session
    String previous_ap = "";
    String previous_action = "";
    for ( String line : allLines ){
    	String[] parts = line.split("\\t");
    	if ( parts.length < 4 )
    		continue;
    	String mac = parts[0];
    	String date_string = parts[1];
    	String action = parts[2];
    	String ap = parts[3];
    	
        if(action.equals(ACTION_SESSION_START)){    //auth request log
            if(ap_auth_tmap.containsKey(ap)){
                //the treemap already has the ap name
                if(ap.equals(previous_ap) && action.equals(previous_action)){
                    //discard
                    if (Utils.debug){
                    	System.out.println("repeating auth log!");
                    }
                    continue;
                } else{
                    // replace the previous one
                	// currently, we do not end an auth (without deauth) with another auth.
                    ap_auth_tmap.put(ap, date_string);
                }
            }
            else{
                //a new ap name
                ap_auth_tmap.put(ap, date_string);
            }
        } else if (action.equals(ACTION_SESSION_END)){    //"Deauth log"
            if(ap_auth_tmap.containsKey(ap)){
                //movement exact
                String start_time_string = ap_auth_tmap.get(ap);
                String end_time_string = date_string;
                DateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT);
                Date start_time = df.parse(start_time_string);
                Date end_time = df.parse(end_time_string);
                long duration = (end_time.getTime() - start_time.getTime())/1000;
                /*
                 * Write into the output file in the format of
                 * USER_MAC, START_TIME, END_TIME, DURATION, AP_NAME
                 */
                roughSessions.add(mac + "\t" + start_time_string + "\t" + end_time_string + "\t" + duration + "\t" + ap);
                //remove the auth time with this ap in the ap_auth_tmap
                ap_auth_tmap.remove(ap);
            } else{    
                //discard
                if (Utils.debug) {
                	System.out.println("Can not find the ap! discard!!!");
                }
                continue;
            }
        } else {
        	/*
        	 * Add other lines as what they are for future usage. 
        	 */
        	roughSessions.add(line);
        }
        previous_ap = ap;
        previous_action = action;
    }

    return roughSessions;
}
 
Example 14
Project: aipo   File: EventlogCsvExportScreen.java View source code 5 votes vote down vote up
/**
 *
 */
@Override
protected String getCSVString(RunData rundata) throws Exception {
  if (ALEipUtils.isAdmin(rundata)) {
    SelectQuery<EipTEventlog> query = Database.query(EipTEventlog.class);

    Date startDay =
      DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.JAPAN).parse(
        rundata.getParameters().get("start_day"));
    Date endDay =
      DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.JAPAN).parse(
        rundata.getParameters().get("end_day"));
    Calendar cal = Calendar.getInstance();
    cal.setTime(endDay);
    cal.set(Calendar.DATE, cal.get(Calendar.DATE) + 1);
    endDay = cal.getTime();
    Expression exp1 =
      ExpressionFactory.greaterOrEqualExp(
        EipTEventlog.EVENT_DATE_PROPERTY,
        startDay);
    Expression exp2 =
      ExpressionFactory.lessExp(EipTEventlog.EVENT_DATE_PROPERTY, endDay);
    query.andQualifier(exp1.andExp(exp2));
    ResultList<EipTEventlog> list = query.getResultList();
    String LINE_SEPARATOR = System.getProperty("line.separator");
    try {
      StringBuffer sb =
        new StringBuffer("\"??\",\"??\",\"???\",\"??\",\"??IP\",\"??\"");
      EventlogResultData data;
      for (ListIterator<EipTEventlog> iterator =
        list.listIterator(list.size()); iterator.hasPrevious();) {
        sb.append(LINE_SEPARATOR);
        data = getResultData(iterator.previous());
        sb.append("\"");
        sb.append(data.getEventDate());
        sb.append("\",\"");
        sb.append(data.getUserFullName());
        sb.append("\",\"");
        sb.append(data.getPortletName());
        sb.append("\",\"");
        sb.append(data.getEventName());
        sb.append("\",\"");
        sb.append(data.getIpAddr());
        sb.append("\",\"");
        sb.append(data.getNote());
        sb.append("\"");
      }
      return sb.toString();
    } catch (Exception e) {
      logger.error("EventlogCsvExportScreen.getCSVString", e);
      return null;
    }
  } else {
    throw new ALPermissionException();
  }
}
 
Example 15
Project: xsm   File: Events.java View source code 5 votes vote down vote up
public void publish( Element root, boolean summarise, String id, StringBuffer s )
{
    s.append( "<p class=\"xsm_news_title\"><b><a name=\"" );
    s.append( root.getAttributeValue( "index" ) + "\">" );
    elements[0].view( root.getChild( "subject" ), s );
    s.append( "</a></b> - " );
    elements[4].view( root.getChild( "author" ), s );
    if ( Events.AUTHOR_PAGES.getBoolean( getDoc() ) )
    {
        String uid = root.getChildText( "uid" );
        if ( uid != null & !uid.equals( "" ) )
        {
            s.append( " [<a href=\"" );
            s.append( getSite().getPrefixUrl() + getPublishedPath() );
            s.append( "/_authors/" + root.getChildText( "uid" ) + ".html\">" );
            s.append( "All my events</a>]" );
        }
    }

    Calendar start = Calendar.getInstance();
    start.setTime( DateTime.parseDateTime( root.getChild( "start" ) ) );
    Calendar stop = Calendar.getInstance();
    stop.setTime( DateTime.parseDateTime( root.getChild( "stop" ) ) );
    DateFormat format = DateFormat.getDateTimeInstance();
    format.setCalendar( start );

    String link = getSite().getPrefixUrl() + getPublishedPath() + "/_months/" + start.get( Calendar.MONTH );
    s.append( " (" );
    s.append( new SimpleDateFormat( "EE" ).format( start.getTime() ) );
    s.append( " <a href=\"" + link + "/" + start.get( Calendar.DATE ) + ".html\">" );
    s.append( start.get( Calendar.DATE ) );
    s.append( "</a> <a href=\"" + link + ".html\">" );
    s.append( new SimpleDateFormat( "MMMM" ).format( start.getTime() ) );
    s.append( "</a> " );
    s.append( start.get( Calendar.YEAR ) );
    s.append( " " );

    if ( start.get( Calendar.YEAR ) == stop.get( Calendar.YEAR ) &&
            start.get( Calendar.DAY_OF_YEAR ) == stop.get( Calendar.DAY_OF_YEAR ) )
    {
        s.append( start.get( Calendar.HOUR_OF_DAY ) );
        s.append( ":" );
        s.append( start.get( Calendar.MINUTE ) );
        s.append( " - " );
        s.append( stop.get( Calendar.HOUR_OF_DAY ) );
        s.append( ":" );
        s.append( stop.get( Calendar.MINUTE ) );
    }
    else
    {
        s.append( "for " );
        if ( start.get( Calendar.YEAR ) != stop.get( Calendar.YEAR ) )
        {
            s.append( stop.get( Calendar.YEAR ) - start.get( Calendar.YEAR ) );
            s.append( " years and" );
        }
        s.append( stop.get( Calendar.DAY_OF_YEAR ) - start.get( Calendar.DAY_OF_YEAR ) );
        s.append( " days" );
    }
    s.append( ")</p>\n" );

    s.append( "<div class=\"xsm_news_article\">" );
    StringBuffer body = new StringBuffer();
    elements[3].publish( root.getChild( "body" ), body );
    if ( summarise )
    {
        s.append( summarise( body.toString() ) );
        s.append( " <a href=\"" + getSite().getPrefixUrl() );
        s.append( getPublishedPath() + "/_events/" + id + ".html\">Read more</a>" );
    }
    else
    {
        s.append( body );
    }
    s.append( "</div>\n" );

    if ( !summarise )
    {
        Element comments = root.getChild( "comments" );
        int commentCount = comments.getChildren( "comment" ).size();
        if ( commentCount > 0 )
        {
            s.append( "<div class=\"xsm_comments\"><p><b>Comments:</b></p>" );
            elements[7].publish( comments, s );
            s.append( "</div>" );
        }
    }
}
 
Example 16
Project: bpel   File: DateTimeSelector.java View source code 5 votes vote down vote up
private void reorderDateWidgetsForLocale() {
	// swap widgets around if our default layout doesn't match locale-specific order!

	int dayPos;
	int monthPos;
	int yearPos;

	DateFormat dateFlatFormat = DateFormat.getDateInstance();//DateFlatFormat.DEFAULT, Locale.JAPAN);
	Date date = new Date();
	StringBuffer junkBuffer = new StringBuffer();

	FieldPosition pos = new FieldPosition(DateFormat.DATE_FIELD);
	dateFlatFormat.format(date, junkBuffer, pos);
	dayPos = pos.getBeginIndex();
	if (Policy.DEBUG) System.out.println(junkBuffer);
	junkBuffer.setLength(0);
	
	pos = new FieldPosition(DateFormat.MONTH_FIELD);
	dateFlatFormat.format(date, junkBuffer, pos);
	monthPos = pos.getBeginIndex();
	junkBuffer.setLength(0);

	pos = new FieldPosition(DateFormat.YEAR_FIELD);
	dateFlatFormat.format(date, junkBuffer, pos);
	yearPos = pos.getBeginIndex();

	Combo left = combo[MONTH];
	Combo middle = combo[DAY];
	Combo right = combo[YEAR];
	
	// The current widget arrangement assumes MDY.
	if (dayPos < monthPos) {
		// it should be DMY or YDM or DYM.
		if (monthPos < yearPos) {
			// D<M<Y
			combo[DAY]=left; combo[MONTH]=middle; combo[YEAR]=right;  // DMY
		} else if (dayPos < yearPos) {
			// D<M  Y<M   D<Y
			combo[DAY]=left; combo[YEAR]=middle; combo[MONTH]=right;  // DYM
		} else {
			// Y<D<M  Y<M   
			combo[YEAR]=left; combo[DAY]=middle; combo[MONTH]=right;  // YDM
		}
	} else {
		if (dayPos < yearPos) {
			// M<D<Y
			combo[MONTH]=left; combo[DAY]=middle; combo[YEAR]=right;  // MDY
		} else if (monthPos < yearPos) {
			// M<D   Y<D   M<Y
			combo[MONTH]=left; combo[YEAR]=middle; combo[DAY]=right;  // MYD
		} else {
			// Y<D   Y<M<D   
			combo[YEAR]=left; combo[MONTH]=middle; combo[DAY]=right;  // YMD
		}
	}
	
}