Java Code Examples for com.ibm.icu.text.SimpleDateFormat#format()

The following examples show how to use com.ibm.icu.text.SimpleDateFormat#format() . 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: DateFormatISO8601.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Format a date/time object.
 * 
 * @param date
 * @param timeZone
 * @return
 * @throws BirtException
 */
public static String format( Date date, TimeZone timeZone ) throws BirtException
{
	if ( date == null  )
	{
		return null;
	}
	
	Object simpleDateFormatter = DateFormatFactory.getPatternInstance( PatternKey.getPatterKey( "yyyy-MM-dd HH:mm:ss.sZ" ) );
	if ( simpleDateFormatter != null )
	{
		try
		{
			SimpleDateFormat sdf = ( (SimpleDateFormat) simpleDateFormatter );
			sdf.setTimeZone( timeZone );
			return sdf.format( date );
		}
		catch ( Exception e1 )
		{
		}
	}
	// for the String can not be parsed, throws a BirtException
	throw new CoreException( ResourceConstants.CONVERT_FAILS, new Object[]{
			date.toString( ), "ISO8601 Format"
	} );
}
 
Example 2
Source File: ExcelUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * format the date with defined time zone.
 * 
 * @param data
 * @param timeZone
 * @return
 */
public static String formatDate( Object data, TimeZone timeZone )
{
	Date date = getDate( data );
	if ( date == null )
	{
		return null;
	}
	SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH );
	if ( timeZone != null && needAdjustWithTimeZone( date ) )
	{
		dateFormat.setTimeZone( timeZone );
	}
	return dateFormat.format( date );
}
 
Example 3
Source File: LoggerSettingManager.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This is a utility function that will create an unique file name with the
 * timestamp information in the file name and append the file name into the
 * directory name. For example, if the directory name is C:\Log, the
 * returned file name will be C:\Log\ReportEngine_2005_02_26_11_26_56.log.
 * 
 * @param directoryName
 *            - the directory name of the log file.
 * @param fileName
 *            the log file name
 * @return An unique Log file name which is the directory name plus the file
 *         name.
 */
private String generateUniqueLogFileName( String directoryName,
		String fileName )
{
	if ( fileName == null )
	{
		SimpleDateFormat df = new SimpleDateFormat( "yyyy_MM_dd_HH_mm_ss" ); //$NON-NLS-1$
		String dateTimeString = df.format( new Date( ) );
		fileName = "ReportEngine_" + dateTimeString + ".log"; //$NON-NLS-1$; $NON-NLS-2$;
	}

	if ( directoryName == null || directoryName.length( ) == 0 )
	{
		return fileName;
	}

	File folder = new File( directoryName );
	File file = new File( folder, fileName );
	return file.getPath( );
}
 
Example 4
Source File: DateFormatService.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Format a long date to localized date
 *
 * @param locale A string representing a specific locale in [lang]_[country (region)] format. e.g., ja_JP, zh_CN
 * @param date Java timestamp format, e.g: 1472728030290
 * @param pattern Date pattern,e.g: [YEAR = "y",QUARTER = "QQQQ"], ABBR_QUARTER =
 *        "QQQ",YEAR_QUARTER = "yQQQQ",YEAR_ABBR_QUARTER = "yQQQ" and so on.
 * @return Localized date
 * @throws L2APIException
 */
public String formatDate(String locale, long date, String pattern) throws L2APIException {
	try{
		ULocale uLocale = new ULocale(locale);
		Date d = new Date(date);
		SimpleDateFormat format = new SimpleDateFormat(pattern, uLocale);
		return format.format(d);
	}catch(Exception e){
		throw new L2APIException(e.getMessage());
	}
}
 
Example 5
Source File: NotificationNewsTableDataModel.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public void render(StringOutput sb, Renderer renderer, Object val, Locale locale, int alignment, String action) {
    Date creationDate = (Date) val;
    SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy", translator.getLocale());
    SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", translator.getLocale());
    // title
    String dateInfo = formatDate.format(creationDate) + " " + formatTime.format(creationDate);
    sb.append(dateInfo);
}
 
Example 6
Source File: NotificationNewsTableDataModel.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public void render(StringOutput sb, Renderer renderer, Object val, Locale locale, int alignment, String action) {
    Date creationDate = (Date) val;
    SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy", translator.getLocale());
    SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", translator.getLocale());
    // title
    String dateInfo = formatDate.format(creationDate) + " " + formatTime.format(creationDate);
    sb.append(dateInfo);
}
 
Example 7
Source File: TimeLabel.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private String getShowText( String type )
{
	//		StringBuffer retValue = new StringBuffer( );

	Calendar calendar = Calendar.getInstance( TimeZone.getTimeZone( id ) );
	calendar.setTimeInMillis( time );

	SimpleDateFormat formatter = new SimpleDateFormat( formatType );
	String result = formatter.format( calendar.getTime( ) );
	return result;

}
 
Example 8
Source File: JavaDateFormatSpecifierImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String format( Calendar c, ULocale lcl )
{
	// ATTN: LOCALE IS UNUSED WHEN THE FORMAT PATTERN IS SPECIFIED
	final SimpleDateFormat sdf = new SimpleDateFormat( getPattern( ), lcl );
	// Only Datetime supports TimeZone
	if ( c instanceof CDateTime && ( (CDateTime) c ).isFullDateTime( ) )
	{
		sdf.setTimeZone( c.getTimeZone( ) );
	}
	return sdf.format( c.getTime( ) );
}
 
Example 9
Source File: OdsUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static String formatDate( Object data )
{
	SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH );
	Date date = getDate( data );
	if(date == null) {
		return null;
	}
	return  dateFormat.format( date );        
}
 
Example 10
Source File: LogDownload.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Prepare all the support resources in one single zip: all the logs, the
 * context.properties, the snapshot of the env variables.
 */
private File prepareAllSupportResources(HttpServletRequest request, HttpServletResponse response) {
	File tmp = null;

	try {
		tmp = File.createTempFile("logs", ".zip");
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tmp));

		try {
			LoggingConfigurator conf = new LoggingConfigurator();
			Collection<String> appenders = conf.getLoggingFiles();

			/*
			 * Store the log files in the zip file
			 */
			for (String appender : appenders) {
				if (appender.endsWith("_WEB"))
					continue;

				File logFile = new File(conf.getFile(appender, true));
				writeEntry(out, logFile.getName(), logFile);
			}

			/*
			 * Now create a copy of the configuration and store it in the
			 * zip file
			 */
			File buf = File.createTempFile("context", ".properties");
			ContextProperties cp = Context.get().getProperties();
			OrderedProperties prop = new OrderedProperties();
			for (String key : cp.getKeys()) {
				if (key.contains("password"))
					continue;
				else
					prop.put(key, cp.get(key));
			}
			prop.store(new FileOutputStream(buf), "Support Request");

			writeEntry(out, "context.properties", buf);
			FileUtil.strongDelete(buf);

			/*
			 * Now create a file with the environment
			 */
			String env = SystemUtil.printEnvironment();
			buf = File.createTempFile("environment", ".txt");
			FileUtil.writeFile(env, buf.getPath());
			writeEntry(out, "environment.txt", buf);
			FileUtil.strongDelete(buf);

			/*
			 * Discover the tomcat's folder
			 */
			ServletContext context = getServletContext();
			File tomcatFile = new File(context.getRealPath("/WEB-INF/web.xml"));
			tomcatFile = tomcatFile.getParentFile().getParentFile().getParentFile().getParentFile();

			/*
			 * Now put the server.xml file
			 */
			File serverFile = new File(tomcatFile.getPath() + "/conf/server.xml");
			writeEntry(out, "tomcat/server.xml", serverFile);

			/*
			 * Now put the most recent tomcat's logs
			 */
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String today = df.format(new Date());
			File logsDir = new File(tomcatFile.getPath() + "/logs");
			File[] files = logsDir.listFiles();
			for (File file : files) {
				if (file.isDirectory() || (!file.getName().toLowerCase().endsWith(".log")
						&& !file.getName().toLowerCase().endsWith(".out")
						&& !file.getName().toLowerCase().endsWith(".txt")))
					continue;

				// store just the logs of today
				if (file.getName().toLowerCase().endsWith(".out")
						|| file.getName().toLowerCase().endsWith(today + ".log")
						|| file.getName().toLowerCase().endsWith(today + ".txt"))
					writeEntry(out, "tomcat/" + file.getName(), file);
			}

			prop.store(new FileOutputStream(buf), "Support Request");
		} finally {
			out.close();
		}
	} catch (Throwable ex) {
		ex.printStackTrace();
	}

	return tmp;
}
 
Example 11
Source File: FormatterImpl.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
public String formatCalWithFormat(final Calendar cal, final String format) {
	SimpleDateFormat sdf = new SimpleDateFormat(format, iLocale);
	sdf.setCalendar(cal);
	return sdf.format(cal.getTime());
}
 
Example 12
Source File: ViewHelper.java    From fess with Apache License 2.0 4 votes vote down vote up
public String createCacheContent(final Map<String, Object> doc, final String[] queries) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final FileTemplateLoader loader = new FileTemplateLoader(ResourceUtil.getViewTemplatePath().toFile());
    final Handlebars handlebars = new Handlebars(loader);

    Locale locale = ComponentUtil.getRequestManager().getUserLocale();
    if (locale == null) {
        locale = Locale.ENGLISH;
    }
    String url = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class);
    if (url == null) {
        url = ComponentUtil.getMessageManager().getMessage(locale, "labels.search_unknown");
    }
    doc.put(fessConfig.getResponseFieldUrlLink(), getUrlLink(doc));
    String createdStr;
    final Date created = DocumentUtil.getValue(doc, fessConfig.getIndexFieldCreated(), Date.class);
    if (created != null) {
        final SimpleDateFormat sdf = new SimpleDateFormat(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
        createdStr = sdf.format(created);
    } else {
        createdStr = ComponentUtil.getMessageManager().getMessage(locale, "labels.search_unknown");
    }
    doc.put(CACHE_MSG, ComponentUtil.getMessageManager().getMessage(locale, "labels.search_cache_msg", url, createdStr));

    doc.put(QUERIES, queries);

    String cache = DocumentUtil.getValue(doc, fessConfig.getIndexFieldCache(), String.class);
    if (cache != null) {
        final String mimetype = DocumentUtil.getValue(doc, fessConfig.getIndexFieldMimetype(), String.class);
        if (!ComponentUtil.getFessConfig().isHtmlMimetypeForCache(mimetype)) {
            cache = StringEscapeUtils.escapeHtml4(cache);
        }
        cache = ComponentUtil.getPathMappingHelper().replaceUrls(cache);
        if (queries != null && queries.length > 0) {
            doc.put(HL_CACHE, replaceHighlightQueries(cache, queries));
        } else {
            doc.put(HL_CACHE, cache);
        }
    } else {
        doc.put(fessConfig.getIndexFieldCache(), StringUtil.EMPTY);
        doc.put(HL_CACHE, StringUtil.EMPTY);
    }

    try {
        final Template template = handlebars.compile(cacheTemplateName);
        final Context hbsContext = Context.newContext(doc);
        return template.apply(hbsContext);
    } catch (final Exception e) {
        logger.warn("Failed to create a cache response.", e);
    }

    return null;
}
 
Example 13
Source File: ParameterValidationUtilTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Tests the validation of the date time type.
 * 
 * @param format
 *            the format choice string
 * @param result
 *            the validation result string
 * 
 * @throws Exception
 * 
 */

private void testDateTimeByFormat( String format, String result )
		throws Exception
{
	// in JAP locale

	ThreadResources.setLocale( ULocale.JAPAN );
	String value = null;
	final SimpleDateFormat formatPattern = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss" ); //$NON-NLS-1$
	Calendar dateCal = Calendar.getInstance( ThreadResources.getLocale( ) );
	dateCal.set( 1998, 8, 13, 20, 1, 44 );
	DateFormatter formatter = new DateFormatter( ThreadResources
			.getLocale( ) );
	formatter.applyPattern( format );
	value = formatter.format( dateCal.getTime( ) );
	String resultJAP = formatPattern.format( ParameterValidationUtil
			.validate( DesignChoiceConstants.PARAM_TYPE_DATETIME, format,
					value, ULocale.JAPAN ) == null
			? null
			: ParameterValidationUtil.validate(
					DesignChoiceConstants.PARAM_TYPE_DATETIME, format,
					value, ULocale.JAPAN ) );
	assertEquals( result, resultJAP );

	// in EN locale

	ThreadResources.setLocale( ULocale.ENGLISH );
	dateCal = Calendar.getInstance( ThreadResources.getLocale( ) );
	dateCal.set( 1998, 8, 13, 20, 1, 44 );
	formatter = new DateFormatter( ThreadResources.getLocale( ) );
	formatter.applyPattern( format );
	value = formatter.format( dateCal.getTime( ) );
	String resultEN = formatPattern.format( ParameterValidationUtil
			.validate( DesignChoiceConstants.PARAM_TYPE_DATETIME, format,
					value, ULocale.ENGLISH ) == null
			? null
			: ParameterValidationUtil.validate(
					DesignChoiceConstants.PARAM_TYPE_DATETIME, format,
					value, ULocale.ENGLISH ) );
	assertEquals( result, resultEN );

	// the two result value is equal.

	assertEquals( resultJAP, resultEN );

	// Test two kind of date format .

	Object obj = ParameterValidationUtil.validate(
			DesignChoiceConstants.PARAM_TYPE_DATETIME, null,
			"1/1/1999 4:50:10 am", ULocale.US ); //$NON-NLS-1$
	assertNotNull( obj );
	assertTrue( obj instanceof Date );

	try
	{
		ParameterValidationUtil.validate(
				DesignChoiceConstants.PARAM_TYPE_DATETIME, null,
				"1999-2-27", ULocale.US ); //$NON-NLS-1$
		fail( );

	}
	catch ( ValidationValueException e )
	{
		assertEquals(
				PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, e
						.getErrorCode( ) );
	}

}
 
Example 14
Source File: APITestCase.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public String getOutputStrForFlatfileTest( int expectedLen,
		IResultSet result, int ColumnCount, String[] columnStr,
		int dateTypeColumnNum ) throws Exception
{

	StringBuffer sBuffer = new StringBuffer( );
	String metaData = "";
	for ( int i = 0; i < ColumnCount; i++ )
	{
		metaData += formatStr( columnStr[i], expectedLen );
	}
	sBuffer.append( metaData );
	sBuffer.append( "\n" );

	while ( result.next( ) )
	{

		String rowData = "";
		for ( int i = 1; i <= ColumnCount; i++ )
		{
			String value;

			if ( result.getString( i ) != null )
			
				// Convert date time according to the format as following
				if ( !result.getString( i ).equals( "DATE" )&& dateTypeColumnNum == i){
					
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss.S" );
						value = sdf.format( result.getDate( i ) );
						}
					
					else
						value = result.getString( i );
			
			else
				value = "";
			rowData += formatStr( value, expectedLen );
		}
		sBuffer.append( rowData );
		sBuffer.append( "\n" );
	}
	return new String( sBuffer );
}
 
Example 15
Source File: DateUtil.java    From olat with Apache License 2.0 4 votes vote down vote up
public static String extractTime(Date date, Locale locale) {
    SimpleDateFormat format = new SimpleDateFormat(emailBodyTimePattern, locale);
    return format.format(date);
}
 
Example 16
Source File: DateUtil.java    From olat with Apache License 2.0 4 votes vote down vote up
public static String extractDate(Date date, Locale locale) {
    SimpleDateFormat format = new SimpleDateFormat(emailBodyDayPattern, locale);
    return format.format(date);
}
 
Example 17
Source File: DateUtil.java    From olat with Apache License 2.0 4 votes vote down vote up
public static String extractTime(Date date, Locale locale) {
    SimpleDateFormat format = new SimpleDateFormat(emailBodyTimePattern, locale);
    return format.format(date);
}
 
Example 18
Source File: DateUtil.java    From olat with Apache License 2.0 4 votes vote down vote up
public static String extractDate(Date date, Locale locale) {
    SimpleDateFormat format = new SimpleDateFormat(emailBodyDayPattern, locale);
    return format.format(date);
}
 
Example 19
Source File: GlobalizationPreferences.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
/**
 * Get the display name for an ID: language, script, territory, currency, timezone...
 * Uses the language priority list to do so.
 *
 * @param id language code, script code, ...
 * @param type specifies the type of the ID: ID_LANGUAGE, etc.
 * @return the display name
 * @draft ICU 3.6
 * @provisional This API might change or be removed in a future release.
 */
public String getDisplayName(String id, int type) {
    String result = id;
    for (ULocale locale : getLocales()) {
        if (!isAvailableLocale(locale, TYPE_GENERIC)) {
            continue;
        }
        switch (type) {
        case ID_LOCALE:
            result = ULocale.getDisplayName(id, locale);
            break;
        case ID_LANGUAGE:
            result = ULocale.getDisplayLanguage(id, locale);
            break;
        case ID_SCRIPT:
            result = ULocale.getDisplayScript("und-" + id, locale);
            break;
        case ID_TERRITORY:
            result = ULocale.getDisplayCountry("und-" + id, locale);
            break;
        case ID_VARIANT:
            // TODO fix variant parsing
            result = ULocale.getDisplayVariant("und-QQ-" + id, locale);
            break;
        case ID_KEYWORD:
            result = ULocale.getDisplayKeyword(id, locale);
            break;
        case ID_KEYWORD_VALUE:
            String[] parts = new String[2];
            Utility.split(id,'=',parts);
            result = ULocale.getDisplayKeywordValue("und@"+id, parts[0], locale);
            // TODO fix to tell when successful
            if (result.equals(parts[1])) {
                continue;
            }
            break;
        case ID_CURRENCY_SYMBOL:
        case ID_CURRENCY:
            Currency temp = new Currency(id);
            result =temp.getName(locale, type==ID_CURRENCY
                                 ? Currency.LONG_NAME
                                 : Currency.SYMBOL_NAME, new boolean[1]);
            // TODO: have method that doesn't take parameter. Add
            // function to determine whether string is choice
            // format.
            // TODO: have method that doesn't require us
            // to create a currency
            break;
        case ID_TIMEZONE:
            SimpleDateFormat dtf = new SimpleDateFormat("vvvv",locale);
            dtf.setTimeZone(TimeZone.getFrozenTimeZone(id));
            result = dtf.format(new Date());
            // TODO, have method that doesn't require us to create a timezone
            // fix other hacks
            // hack for couldn't match

            boolean isBadStr = false;
            // Matcher badTimeZone = Pattern.compile("[A-Z]{2}|.*\\s\\([A-Z]{2}\\)").matcher("");
            // badtzstr = badTimeZone.reset(result).matches();
            String teststr = result;
            int sidx = result.indexOf('(');
            int eidx = result.indexOf(')');
            if (sidx != -1 && eidx != -1 && (eidx - sidx) == 3) {
                teststr = result.substring(sidx+1, eidx);
            }
            if (teststr.length() == 2) {
                isBadStr = true;
                for (int i = 0; i < 2; i++) {
                    char c = teststr.charAt(i);
                    if (c < 'A' || 'Z' < c) {
                        isBadStr = false;
                        break;
                    }
                }
            }
            if (isBadStr) {
                continue;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown type: " + type);
        }

        // TODO need better way of seeing if we fell back to root!!
        // This will not work at all for lots of stuff
        if (!id.equals(result)) {
            return result;
        }
    }
    return result;
}
 
Example 20
Source File: LogReader.java    From org.openntf.domino with Apache License 2.0 2 votes vote down vote up
/**
 * Converts the date to a human readable format
 * 
 * @param date
 *            long
 * @return String date in format yyyyMMdd'T'hhmmss
 */
public static String readableDate(final long date) {
	String DATE_FORMAT = "yyyyMMdd'T'hhmmss";
	SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
	return sdf.format(date);
}