com.ibm.icu.text.DateFormat Java Examples

The following examples show how to use com.ibm.icu.text.DateFormat. 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: GlobalizationPreferences.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
/**
 * This function can be overridden by subclasses to use different heuristics.
 * <b>It MUST return a 'safe' value,
 * one whose modification will not affect this object.</b>
 *
 * @param dateStyle
 * @param timeStyle
 * @draft ICU 3.6
 * @provisional This API might change or be removed in a future release.
 */
protected DateFormat guessDateFormat(int dateStyle, int timeStyle) {
    DateFormat result;
    ULocale dfLocale = getAvailableLocale(TYPE_DATEFORMAT);
    if (dfLocale == null) {
        dfLocale = ULocale.ROOT;
    }
    if (timeStyle == DF_NONE) {
        result = DateFormat.getDateInstance(getCalendar(), dateStyle, dfLocale);
    } else if (dateStyle == DF_NONE) {
        result = DateFormat.getTimeInstance(getCalendar(), timeStyle, dfLocale);
    } else {
        result = DateFormat.getDateTimeInstance(getCalendar(), dateStyle, timeStyle, dfLocale);
    }
    return result;
}
 
Example #2
Source File: DateTimeFormatObject.java    From es6draft with MIT License 6 votes vote down vote up
private DateFormat createDateFormat() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    // calendar and numberingSystem are already handled in language-tag
    // assert locale.getKeywordValue("calendar").equals(calendar);
    // assert locale.getKeywordValue("numbers").equals(numberingSystem);
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern.get(), locale);
    if (timeZone != null) {
        dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
    }
    Calendar calendar = dateFormat.getCalendar();
    if (calendar instanceof GregorianCalendar) {
        // format uses a proleptic Gregorian calendar with no year 0
        GregorianCalendar gregorian = (GregorianCalendar) calendar;
        gregorian.setGregorianChange(new Date(Long.MIN_VALUE));
    }
    return dateFormat;
}
 
Example #3
Source File: DateTimeFormatConstructor.java    From es6draft with MIT License 6 votes vote down vote up
/**
 * 12.1.6 PartitionDateTimePattern ( dateTimeFormat, x )
 * 
 * @param dateTimeFormat
 *            the date format object
 * @param date
 *            the date object
 * @return the formatted date-time object
 */
private static List<Map.Entry<String, String>> PartitionDateTimePattern(DateTimeFormatObject dateTimeFormat,
        Date date) {
    ArrayList<Map.Entry<String, String>> parts = new ArrayList<>();
    DateFormat dateFormat = dateTimeFormat.getDateFormat();
    AttributedCharacterIterator iterator = dateFormat.formatToCharacterIterator(date);
    StringBuilder sb = new StringBuilder();
    for (char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) {
        sb.append(ch);
        if (iterator.getIndex() + 1 == iterator.getRunLimit()) {
            Iterator<Attribute> keyIterator = iterator.getAttributes().keySet().iterator();
            String key;
            if (keyIterator.hasNext()) {
                key = fieldToString((DateFormat.Field) keyIterator.next());
            } else {
                key = "literal";
            }
            String value = sb.toString();
            sb.setLength(0);
            parts.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
        }
    }
    return parts;
}
 
Example #4
Source File: DateUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Check whether dateStr can be correctly converted to Date in 
 * format of DateFormat.SHORT. Here one point must be noticed that
 * dateStr should firstly be able to be converted to Date.
 * 
 * @param df
 * @param dateStr
 * @return checkinfo
 */
public static boolean checkValid( DateFormat df, String dateStr )
{
	assert df != null;
	assert dateStr != null;
	
	boolean isValid = true;
	if ( df instanceof SimpleDateFormat )
	{			
		String[] dateResult = splitDateStr( dateStr );

		SimpleDateFormat sdf = (SimpleDateFormat) df;
		String pattern = sdf.toPattern( );
		String[] patternResult = splitDateStr( pattern );
		
		if ( dateResult != null && patternResult != null )
		{
			isValid = isMatch( dateResult, patternResult );
		}
	}

	return isValid;
}
 
Example #5
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses a date/time string
 *
 * @param source
 * @param locale
 * @param timeZone
 * @return
 * @throws BirtException
 */
public static Date toDate( String source, ULocale locale, TimeZone timeZone )
		throws BirtException
{
	DateFormat dateFormat = getDateFormatObject( source, locale, timeZone );
	Date resultDate = null;
	try
	{
		resultDate = dateFormat.parse( source );
		return resultDate;
	}
	catch ( ParseException e )
	{
		throw new CoreException(
				ResourceConstants.CONVERT_FAILS,
				new Object[]{
						source.toString( ), "Date"
				} );
	}
}
 
Example #6
Source File: DateFormatISO8601.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parse a date/time string.
 *
 * @param source
 * @return
 * @throws ParseException
 */
public static Date parse( String source, TimeZone timeZone ) throws BirtException,
		ParseException
{
	DateFormat dateFormat = getSimpleDateFormat( source, timeZone );
	Date resultDate = null;
	try
	{
		if ( timeZone != null )
		{
			dateFormat.setTimeZone( timeZone );
		}
		if ( dateFormat != null )
		{
			source = cleanDate( source );
			resultDate = dateFormat.parse( source );
		}
		return resultDate;
	}
	catch ( ParseException e )
	{
		throw new CoreException( ResourceConstants.CONVERT_FAILS,
				new Object[]{source.toString( ), "Date"} );
	}
}
 
Example #7
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public static java.sql.Timestamp toTimestampFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		Date date = DateFormat.getInstance( ).parse( s );
		return new Timestamp( date.getTime( ) );
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #8
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public static java.sql.Time toTimeFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		Date date = DateFormat.getInstance( ).parse( s );
		return new Time( date.getTime( ) );
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #9
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public static java.sql.Date toDateFromString( String s ) throws OdaException
{
	if ( s == null )
	{
		return null;
	}
	try
	{
		Date date = DateFormat.getInstance( ).parse( s );
		return new java.sql.Date( date.getTime( ) );
	}
	catch ( ParseException e )
	{
		throw new OdaException( e );
	}
}
 
Example #10
Source File: DateFormatSpecifierImpl.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 
 * @return
 * @throws UndefinedValueException
 */
private final int getJavaType( ) throws ChartException
{
	switch ( getType( ).getValue( ) )
	{
		case DateFormatType.SHORT :
			return DateFormat.SHORT;
		case DateFormatType.MEDIUM :
			return DateFormat.MEDIUM;
		case DateFormatType.LONG :
			return DateFormat.LONG;
		case DateFormatType.FULL :
			return DateFormat.FULL;
	}
	return 0;
}
 
Example #11
Source File: BaseRenderer.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Formats value in URL parameters so that it can be read in server
 * 
 * @param value
 * @return
 */
private String formatURLValue( Object value )
{
	if ( value instanceof Calendar )
	{
		// Bugzilla#215442 fix a parse issue to date
		// Bugzilla#245920 Just using default locale to format date string
		// to avoid passing locale-specific value for drill-through.
		return DateFormat.getDateInstance( DateFormat.LONG ).format( value );
	}
	if ( value instanceof Number )
	{
		// Do not output decimal for integer value, and also avoid double
		// precision error for double value
		Number num = (Number) value;
		if ( ChartUtil.mathEqual( num.doubleValue( ), num.intValue( ) ) )
		{
			return String.valueOf( num.intValue( ) );
		}
		return String.valueOf( ValueFormatter.normalizeDouble( num.doubleValue( ) ) );
	}
	return ChartUtil.stringValue( value );
}
 
Example #12
Source File: DateFormatFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets DateFormat instance allocated to the current thread for the given
 * date style, timestyle and locale. Returned instance is safe to use
 * 
 */
public static DateFormat getDateTimeInstance( int dateStyle, int timeStyle,
		ULocale locale )
{
	assert locale != null;

	// Create key string for cache lookup
	String keyStr = locale.getName( )
			+ "/" + Integer.toString( dateStyle ) + "/"
			+ Integer.toString( timeStyle );

	HashMap tlsMap = (HashMap) tlsCache.get( );
	assert tlsMap != null;

	DateFormat result = (DateFormat) tlsMap.get( keyStr );

	// Create new instance and add to cache if no instance available for
	// current thread/style/locale combination
	if ( result == null )
	{
		if ( timeStyle == NO_TIME_STYLE )
			result = DateFormat.getDateInstance( dateStyle,
					locale.toLocale( ) );
		else
			result = DateFormat.getDateTimeInstance( dateStyle,
					timeStyle,
					locale.toLocale( ) );
		tlsMap.put( keyStr, result );
	}

	return result;

}
 
Example #13
Source File: DominoFormatter.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the date from string.
 * 
 * @param dateString
 *            the date string
 * @return the date
 */
public Date parseDateFromString(final String dateString) {
	DateFormat df = getDateTimeFormat();
	synchronized (df) {
		try {
			return df.parse(dateString);
		} catch (ParseException e) {
			DominoUtils.handleException(e);
			return null;
		}
	}
}
 
Example #14
Source File: FormatterImpl.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
private int transTimeFormat(final int timeFormat) {
	if (timeFormat == TIMEFORMAT_MEDIUM)
		return DateFormat.MEDIUM;
	if (timeFormat == TIMEFORMAT_SHORT)
		return DateFormat.SHORT;
	return DateFormat.LONG;
}
 
Example #15
Source File: DateTimeFormatObject.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * Returns the ICU {@link DateFormat} instance.
 * 
 * @return the DateFormat instance
 */
public DateFormat getDateFormat() {
    if (dateFormat == null) {
        dateFormat = createDateFormat();
    }
    return dateFormat;
}
 
Example #16
Source File: ChineseCalendar.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @stable ICU 4.2
 */
protected DateFormat handleGetDateFormat(String pattern, String override, ULocale locale) {
    // Note: ICU 50 or later versions no longer use ChineseDateFormat.
    // The super class's handleGetDateFormat will create an instance of
    // SimpleDateFormat which supports Chinese calendar date formatting
    // since ICU 49.

    //return new ChineseDateFormat(pattern, override, locale);
    return super.handleGetDateFormat(pattern, override, locale);
}
 
Example #17
Source File: DateTimeFormatConstructor.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * Retrieve the default hour format character for the supplied locale.
 * 
 * @param locale
 *            the locale
 * @return the hour format character
 * @see <a href="http://bugs.icu-project.org/trac/ticket/9997">ICU bug 9997</a>
 */
private static char defaultHourFormat(ULocale locale) {
    // Use short time format, just as ICU4J does internally. And as suggested in
    // <http://unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems>.
    SimpleDateFormat df = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    Skeleton skeleton = Skeleton.fromPattern(df.toPattern());
    if (skeleton.has(DateField.Hour)) {
        return skeleton.getSymbol(DateField.Hour);
    }
    return 'H';
}
 
Example #18
Source File: DataTypeUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convert string to date with check.
 * JDK may do incorrect converse, for example:
 * 		2005/1/1 Local.US, format pattern is MM/dd/YY.
 * Above conversion can be done without error, but obviously
 * the result is not right. This method will do such a simple check,
 * in DateFormat.SHORT case instead of all cases.
 * 		Year is not lower than 0.
 * 		Month is from 1 to 12.
 * 		Day is from 1 to 31.  
 * @param source
 * @param locale
 * @return Date
 * @throws BirtException
 */
public static Date toDateWithCheck( String source, ULocale locale )
		throws BirtException
{
	DateFormat dateFormat = DateFormatFactory.getDateInstance( DateFormat.SHORT,
			locale );
	Date resultDate = null;
	try
	{
		resultDate = dateFormat.parse( source );
	}
	catch ( ParseException e )
	{
		return toDate( source, locale );
	}

	// check whether conversion is correct
	if ( DateUtil.checkValid( dateFormat, source ) == false )
	{
		throw new CoreException( 
				ResourceConstants.CONVERT_FAILS,
				new Object[]{
						source.toString( ), "Date"
				});
	}

	return resultDate;
}
 
Example #19
Source File: RelativeDateFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private MessageFormat initializeCombinedFormat(Calendar cal, ULocale locale) {
    String pattern;
    ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(
        ICUData.ICU_BASE_NAME, locale);
    String resourcePath = "calendar/" + cal.getType() + "/DateTimePatterns";
    ICUResourceBundle patternsRb= rb.findWithFallback(resourcePath);
    if (patternsRb == null && !cal.getType().equals("gregorian")) {
        // Try again with gregorian, if not already attempted.
        patternsRb = rb.findWithFallback("calendar/gregorian/DateTimePatterns");
    }

    if (patternsRb == null || patternsRb.getSize() < 9) {
        // Undefined or too few elements.
        pattern = "{1} {0}";
    } else {
        int glueIndex = 8;
        if (patternsRb.getSize() >= 13) {
          if (fDateStyle >= DateFormat.FULL && fDateStyle <= DateFormat.SHORT) {
              glueIndex += fDateStyle + 1;
          } else
              if (fDateStyle >= DateFormat.RELATIVE_FULL &&
                  fDateStyle <= DateFormat.RELATIVE_SHORT) {
                  glueIndex += fDateStyle + 1 - DateFormat.RELATIVE;
              }
        }
        int elementType = patternsRb.get(glueIndex).getType();
        if (elementType == UResourceBundle.ARRAY) {
            pattern = patternsRb.get(glueIndex).getString(0);
        } else {
            pattern = patternsRb.getString(glueIndex);
        }
    }
    combinedFormatHasDateAtStart = pattern.startsWith("{1}");
    fCombinedFormat = new MessageFormat(pattern, locale);
    return fCombinedFormat;
}
 
Example #20
Source File: SendMailFormatterForCourse.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public String getBody(final InfoMessage msg) {
    final BusinessControlFactory bCF = BusinessControlFactory.getInstance();
    final List<ContextEntry> ceList = bCF.createCEListFromString(businessPath);
    final String busPath = NotificationHelper.getBusPathStringAsURIFromCEList(ceList);

    final String author = getUserService().getFirstAndLastname(msg.getAuthor().getUser());
    final String date = DateFormat.getDateInstance(DateFormat.MEDIUM, translator.getLocale()).format(msg.getCreationDate());
    final String link = Settings.getServerContextPathURI() + "/url/" + busPath;
    return translator.translate("mail.body", new String[] { courseTitle, author, date, msg.getMessage(), link });
}
 
Example #21
Source File: DateFormatWrapperFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a preferred format specifier for tick labels that represent axis
 * values that will be computed based on the difference between cdt1 and
 * cdt2
 * 
 * @param iUnit
 *            The unit for which a preferred pattern is being requested
 * @param locale
 *            The locale for format style
 * @param keepHierarchy
 *            indicates if the format should keep hierarchy
 * 
 * @return A preferred datetime format for the given unit
 */
public static final IDateFormatWrapper getPreferredDateFormat( int iUnit,
		ULocale locale, boolean keepHierarchy )
{
	IDateFormatWrapper df = null;
	String pattern = ChartUtil.createDefaultFormatPattern( iUnit,
			keepHierarchy );
	df = new CommonDateFormatWrapper( new SimpleDateFormat( pattern, locale ) );
	// Special cases for dynamic patterns
	switch ( iUnit )
	{
		case Calendar.MONTH :
			if ( keepHierarchy )
			{
				df = new MonthDateFormat( locale );
			}
			break;
		case Calendar.DAY_OF_MONTH :// Same as DATE
			if ( keepHierarchy )
			{
				df = new CommonDateFormatWrapper( DateFormat.getDateInstance( DateFormat.MEDIUM,
						locale ) );
			}
			break;
	}
	return df;
}
 
Example #22
Source File: DateFormatWrapperFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String toLocalizedPattern( )
{
	DateFormat df = DateFormat.getDateInstance( DateFormat.LONG, locale );
	if ( df instanceof SimpleDateFormat )
	{
		return ( (SimpleDateFormat) df ).toLocalizedPattern( )
				+ "\n"  //$NON-NLS-1$
				+ new SimpleDateFormat( "HH:mm", locale ).toLocalizedPattern( ); //$NON-NLS-1$
	}
	return "MMMM d, yyyy HH:mm";  //$NON-NLS-1$
}
 
Example #23
Source File: DateFormatWrapperFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String toLocalizedPattern( )
{
	DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM,
			locale );
	if ( df instanceof SimpleDateFormat )
	{
		String pattern = ( (SimpleDateFormat) df ).toLocalizedPattern( );
		return pattern.replaceAll( "(-|/)?d+(\\.|,|/|-)?\\s?", "" ).trim( ); //$NON-NLS-1$ //$NON-NLS-2$  
	}
	return "MMM yyyy";  //$NON-NLS-1$
}
 
Example #24
Source File: DateFormatFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets DateFormat instance allocated to the current thread for the given
 * date style, timestyle and locale. Returned instance is safe to use
 * 
 */
public static DateFormat getDateTimeInstance( int dateStyle, int timeStyle,
		ULocale locale )
{
	assert locale != null;

	// Create key string for cache lookup
	String keyStr = locale.getName( )
			+ "/" + Integer.toString( dateStyle ) + "/" //$NON-NLS-1$ //$NON-NLS-2$
			+ Integer.toString( timeStyle );

	HashMap tlsMap = (HashMap) tlsCache.get( );
	assert tlsMap != null;

	DateFormat result = (DateFormat) tlsMap.get( keyStr );

	// Create new instance and add to cache if no instance available for
	// current thread/style/locale combination
	if ( result == null )
	{
		if ( timeStyle == NO_TIME_STYLE )
			result = DateFormat.getDateInstance( dateStyle,
					locale.toLocale( ) );
		else
			result = DateFormat.getDateTimeInstance( dateStyle,
					timeStyle,
					locale.toLocale( ) );
		result.setLenient( false );
		tlsMap.put( keyStr, result );
	}

	return result;

}
 
Example #25
Source File: DateTimePropertyType.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validates the locale-dependent value for the date time type, validate the
 * <code>value</code> in the locale-dependent way and convert the
 * <code>value</code> into a Date object.
 * 
 * @return object of type Date or null if <code>value</code> is null.
 */

public Object validateInputString( Module module, DesignElement element,
		PropertyDefn defn, String value ) throws PropertyValueException
{
	if ( StringUtil.isBlank( value ) )
	{
		return null;
	}

	// Parse the input in locale-dependent way.
	ULocale locale = module == null ? ThreadResources.getLocale( ) : module
			.getLocale( );
	DateFormat formatter = DateFormat.getDateInstance( DateFormat.SHORT,
			locale );
	try
	{
		return formatter.parse( value );
	}
	catch ( ParseException e )
	{
		logger.log( Level.SEVERE, "Invalid date value:" + value ); //$NON-NLS-1$
		throw new PropertyValueException( value,
				PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE,
				DATE_TIME_TYPE );
	}
}
 
Example #26
Source File: DateFormatWrapperFactory.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public CommonDateFormatWrapper( DateFormat formater )
{
	this.formater = formater;
}
 
Example #27
Source File: DateFormatWrapperFactory.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public String format( Date date )
{
	StringBuffer str = new StringBuffer( );
	FieldPosition pos = new FieldPosition( DateFormat.DATE_FIELD );
	DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM, locale );
	if ( tz != null )
	{
		df.setTimeZone( tz );
	}
	df.format( date, str, pos );
	int endIndex;
	if ( pos.getEndIndex( ) >= str.length( ) )
	{
		endIndex = pos.getEndIndex( );
	}
	else
	{
		endIndex = pos.getEndIndex( )
				+ ( str.charAt( pos.getEndIndex( ) ) == ',' ? 2 : 1 );
	}
	if ( endIndex >= str.length( ) ) // means date is the last one, need
										// to remove separator
	{
		endIndex = pos.getBeginIndex( );
		while ( endIndex > 0 )
		{
			char ch = str.charAt( endIndex - 1 );
			if ( ch == ' '
					|| ch == ',' || ch == '/' || ch == '-' || ch == '.' )
			{
				endIndex--;
			}
			else
			{
				break;
			}
		}
		return str.substring( 0, endIndex );
	}
	return str.substring( 0, pos.getBeginIndex( ) )
			+ str.substring( endIndex );
}
 
Example #28
Source File: FormatterImpl.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
public String formatCalTimeOnly(final Calendar cal, final int timeFormat) {
	DateFormat df = DateFormat.getTimeInstance(transTimeFormat(timeFormat), iLocale);
	df.setCalendar(cal);
	return df.format(cal.getTime());
}
 
Example #29
Source File: FormatterImpl.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
public String formatCalDateOnly(final Calendar cal) {
	DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, iLocale);
	df.setCalendar(cal);
	return df.format(cal.getTime());
}
 
Example #30
Source File: FormatterImpl.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
public String formatCalDateTime(final Calendar cal, final int timeFormat) {
	DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, transTimeFormat(timeFormat), iLocale);
	df.setCalendar(cal);
	return df.format(cal.getTime());
}