Java源码示例:com.ibm.icu.text.DateFormat
示例1
/**
* 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;
}
示例2
/**
* 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 );
}
示例3
/**
*
* @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;
}
示例4
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 );
}
}
示例5
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 );
}
}
示例6
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 );
}
}
示例7
/**
* 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"} );
}
}
示例8
/**
* 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"
} );
}
}
示例9
/**
* 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;
}
示例10
/**
* 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;
}
示例11
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;
}
示例12
/**
* {@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);
}
示例13
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;
}
示例14
@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 });
}
示例15
/**
* 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;
}
示例16
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$
}
示例17
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$
}
示例18
/**
* 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;
}
示例19
/**
* 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 );
}
}
示例20
/**
* 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;
}
示例21
/**
* 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;
}
示例22
/**
* 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';
}
示例23
/**
* Returns the ICU {@link DateFormat} instance.
*
* @return the DateFormat instance
*/
public DateFormat getDateFormat() {
if (dateFormat == null) {
dateFormat = createDateFormat();
}
return dateFormat;
}
示例24
private int transTimeFormat(final int timeFormat) {
if (timeFormat == TIMEFORMAT_MEDIUM)
return DateFormat.MEDIUM;
if (timeFormat == TIMEFORMAT_SHORT)
return DateFormat.SHORT;
return DateFormat.LONG;
}
示例25
/**
* 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;
}
}
}
示例26
@Override
public StringBuffer format(Calendar cal, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
String relativeDayString = null;
DisplayContext capitalizationContext = getContext(DisplayContext.Type.CAPITALIZATION);
if (fDateStyle != DateFormat.NONE) {
// calculate the difference, in days, between 'cal' and now.
int dayDiff = dayDifference(cal);
// look up string
relativeDayString = getStringForDay(dayDiff);
}
if (fDateTimeFormat != null) {
if (relativeDayString != null && fDatePattern != null &&
(fTimePattern == null || fCombinedFormat == null || combinedFormatHasDateAtStart) ) {
// capitalize relativeDayString according to context for relative, set formatter no context
if ( relativeDayString.length() > 0 && UCharacter.isLowerCase(relativeDayString.codePointAt(0)) &&
(capitalizationContext == DisplayContext.CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
(capitalizationContext == DisplayContext.CAPITALIZATION_FOR_UI_LIST_OR_MENU && capitalizationOfRelativeUnitsForListOrMenu) ||
(capitalizationContext == DisplayContext.CAPITALIZATION_FOR_STANDALONE && capitalizationOfRelativeUnitsForStandAlone) )) {
if (capitalizationBrkIter == null) {
// should only happen when deserializing, etc.
capitalizationBrkIter = BreakIterator.getSentenceInstance(fLocale);
}
relativeDayString = UCharacter.toTitleCase(fLocale, relativeDayString, capitalizationBrkIter,
UCharacter.TITLECASE_NO_LOWERCASE | UCharacter.TITLECASE_NO_BREAK_ADJUSTMENT);
}
fDateTimeFormat.setContext(DisplayContext.CAPITALIZATION_NONE);
} else {
// set our context for the formatter
fDateTimeFormat.setContext(capitalizationContext);
}
}
if (fDateTimeFormat != null && (fDatePattern != null || fTimePattern != null)) {
// The new way
if (fDatePattern == null) {
// must have fTimePattern
fDateTimeFormat.applyPattern(fTimePattern);
fDateTimeFormat.format(cal, toAppendTo, fieldPosition);
} else if (fTimePattern == null) {
// must have fDatePattern
if (relativeDayString != null) {
toAppendTo.append(relativeDayString);
} else {
fDateTimeFormat.applyPattern(fDatePattern);
fDateTimeFormat.format(cal, toAppendTo, fieldPosition);
}
} else {
String datePattern = fDatePattern; // default;
if (relativeDayString != null) {
// Need to quote the relativeDayString to make it a legal date pattern
datePattern = "'" + relativeDayString.replace("'", "''") + "'";
}
StringBuffer combinedPattern = new StringBuffer("");
fCombinedFormat.format(new Object[] {fTimePattern, datePattern}, combinedPattern, new FieldPosition(0));
fDateTimeFormat.applyPattern(combinedPattern.toString());
fDateTimeFormat.format(cal, toAppendTo, fieldPosition);
}
} else if (fDateFormat != null) {
// A subset of the old way, for serialization compatibility
// (just do the date part)
if (relativeDayString != null) {
toAppendTo.append(relativeDayString);
} else {
fDateFormat.format(cal, toAppendTo, fieldPosition);
}
}
return toAppendTo;
}
示例27
public CommonDateFormatWrapper( DateFormat formater )
{
this.formater = formater;
}
示例28
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 );
}
示例29
/**
*
*/
@Test
public void testResultIteratorFindGroup3( ) throws Exception
{
String[] bindingNameGroup = new String[]{
"GROUP_SALE_DATE", "GROUP_AMOUNT"
};
IBaseExpression[] bindingExprGroup = new IBaseExpression[]{
new ScriptExpression( "dataSetRow[\"SALE_DATE\"]" ),
new ScriptExpression( "dataSetRow.AMOUNT" )
};
GroupDefinition[] groupDefn = new GroupDefinition[]{
new GroupDefinition( "group1" ), new GroupDefinition( "group2" )
};
groupDefn[0].setKeyExpression( "row.GROUP_SALE_DATE" );
groupDefn[1].setKeyExpression( "row.GROUP_AMOUNT" );
String[] bindingNameRow = new String[]{
"ROW_COUNTRY",
"ROW_CITY",
"ROW_SALE_DATE",
"ROW_AMOUNT"
};
IBaseExpression[] bindingExprRow = new IBaseExpression[]{
new ScriptExpression( "dataSetRow[\"COUNTRY\"]", 0 ),
new ScriptExpression( "dataSetRow.CITY", 0 ),
new ScriptExpression( "dataSetRow.SALE_DATE", 0 ),
new ScriptExpression( "dataSetRow.AMOUNT", 0 )
};
QueryDefinition queryDefn = this.createQuery( bindingNameGroup,
bindingExprGroup,
groupDefn,
null,
null,
null,
null,
null,
null,
bindingNameRow,
bindingExprRow );
IResultIterator it = executeQuery( queryDefn );
it.next( );
DateFormat df = DateFormat.getDateInstance( DateFormat.SHORT, Locale.US );
testFindGroup( it, new Object[]{
df.format( df.parse( "05/01/2004" ) )
}, 5 );
testFindGroup( it, new Object[]{
df.format( df.parse( "06/01/2004" ) ), "100"
}, 3 );
testFindGroup( it, new Object[]{
df.format( df.parse( "06/01/2004" ) ), new Integer( 100 )
}, 3 );
testFindGroup( it, new Object[]{
df.format( df.parse( "06/05/2004" ) ), "400"
}, 1 );
try
{
testFindGroup( it, new Object[]{
"CHINA", "abc"
}, 6 );
fail( "Should convert fails" );
}
catch ( BirtException e )
{
System.out.println( e.getLocalizedMessage( ) );
}
}
示例30
/**
* @deprecated use getDateFormatObject instead
*/
public static DateFormat getDateFormat( String source, ULocale locale, TimeZone timeZone )
throws BirtException
{
return getDateFormatObject( source, locale, timeZone );
}