Java Code Examples for java.text.DateFormat#getDateInstance()

The following examples show how to use java.text.DateFormat#getDateInstance() . 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: Bug8074791.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] arg) {
    int errors = 0;

    DateFormat df = DateFormat.getDateInstance(LONG, FINNISH);
    Date jan20 = new GregorianCalendar(2015, JANUARY, 20).getTime();
    String str = df.format(jan20).toString();
    // Extract the month name (locale data dependent)
    String month = str.replaceAll(".+\\s([a-z]+)\\s\\d+$", "$1");
    if (!month.equals(JAN_FORMAT)) {
        errors++;
        System.err.println("wrong format month name: got '" + month
                           + "', expected '" + JAN_FORMAT + "'");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("LLLL", FINNISH); // stand-alone month name
    month = sdf.format(jan20);
    if (!month.equals(JAN_STANDALONE)) {
        errors++;
        System.err.println("wrong stand-alone month name: got '" + month
                           + "', expected '" + JAN_STANDALONE + "'");
    }

    if (errors > 0) {
        throw new RuntimeException();
    }
}
 
Example 2
Source File: Bug4807540.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    Locale si = new Locale("sl", "si");

    String expected = "30.4.2008";
    DateFormat dfSi = DateFormat.getDateInstance (DateFormat.MEDIUM, si);

    String siString = new String (dfSi.format(new Date(108, Calendar.APRIL, 30)));

    if (expected.compareTo(siString) != 0) {
        throw new RuntimeException("Error: " + siString  + " should be " + expected);
    }
}
 
Example 3
Source File: DateTickUnit.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A utility method to put a default in place if a null formatter is
 * supplied.
 *
 * @param formatter  the formatter (<code>null</code> permitted).
 *
 * @return The formatter if it is not null, otherwise a default.
 */
private static DateFormat notNull(DateFormat formatter) {
    if (formatter == null) {
        return DateFormat.getDateInstance(DateFormat.SHORT);
    }
    else {
        return formatter;
    }
}
 
Example 4
Source File: Bug8037343.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] arg)
{
    final Locale esDO = new Locale("es", "DO");
    final String expectedShort = "31/03/12";
    final String expectedMedium = "31/03/2012";

    int errors = 0;
    DateFormat format;
    String result;

    Calendar cal = Calendar.getInstance(esDO);
    cal.set(Calendar.DAY_OF_MONTH, 31);
    cal.set(Calendar.MONTH, Calendar.MARCH);
    cal.set(Calendar.YEAR, 2012);

    format = DateFormat.getDateInstance(DateFormat.SHORT, esDO);
    result = format.format(cal.getTime());
    if (!expectedShort.equals(result)) {
        System.out.println(String.format("Short Date format for es_DO is not as expected. Expected: [%s] Actual: [%s]", expectedShort, result));
        errors++;
    }

    format = DateFormat.getDateInstance(DateFormat.MEDIUM, esDO);
    result = format.format(cal.getTime());
    if (!expectedMedium.equals(result)) {
        System.out.println(String.format("Medium Date format for es_DO is not as expected. Expected: [%s] Actual: [%s]", expectedMedium, result));
        errors++;
    }

    if (errors > 0) {
        throw new RuntimeException();
    }
}
 
Example 5
Source File: Lang_50_FastDateFormat_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Gets a date formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date formatter
 * @throws IllegalArgumentException if the Locale has no date
 *  pattern defined
 */
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }

    if (locale != null) {
        key = new Pair(key, locale);
    }


    FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateInstanceCache.put(key, format);
            
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 6
Source File: Arja_00117_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Gets a date formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date formatter
 * @throws IllegalArgumentException if the Locale has no date
 *  pattern defined
 */
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }

    if (locale != null) {
        key = new Pair(key, locale);
    }


    FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateInstanceCache.put(key, format);
            
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 7
Source File: LocaleDateFormats.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "dateFormats")
public void testDateFormat(Locale loc, int style, int year, int month, int date, String expectedString) {
    Calendar cal = Calendar.getInstance(loc);
    cal.set(year, month-1, date);
    // Create date formatter based on requested style and test locale
    DateFormat df = DateFormat.getDateInstance(style, loc);
    // Test the date format
    assertEquals(df.format(cal.getTime()), expectedString);
}
 
Example 8
Source File: FormatCache.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Gets a date/time format for the specified styles and locale.</p>
 * 
 * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format
 * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format
 * @param locale  The non-null locale of the desired format
 * @return a localized standard date/time format
 * @throws IllegalArgumentException if the Locale has no date/time pattern defined
 */
public static String getPatternForStyle(Integer dateStyle, Integer timeStyle, Locale locale) {
    MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale);

    String pattern = cDateTimeInstanceCache.get(key);
    if (pattern == null) {
        try {
            DateFormat formatter;
            if (dateStyle == null) {
                formatter = DateFormat.getTimeInstance(timeStyle, locale);                    
            }
            else if (timeStyle == null) {
                formatter = DateFormat.getDateInstance(dateStyle, locale);                    
            }
            else {
                formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
            }
            pattern = ((SimpleDateFormat)formatter).toPattern();
            String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern);
            if (previous != null) {
                // even though it doesn't matter if another thread put the pattern
                // it's still good practice to return the String instance that is
                // actually in the ConcurrentMap
                pattern= previous;
            }
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date time pattern for locale: " + locale);
        }
    }
    return pattern;
}
 
Example 9
Source File: DateDemo03.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) {
    DateFormat df1 = null; // 声明一个DateFormat
    DateFormat df2 = null; // 声明一个DateFormat
    df1 = DateFormat.getDateInstance(); // 得到日期的DateFormat对象
    df2 = DateFormat.getDateTimeInstance(); // 得到日期时间的DateFormat对象
    System.out.println("DATE:" + df1.format(new Date())); // 按照日期格式化
    System.out.println("DATETIME:" + df2.format(new Date())); // 按照日期时间格式化
}
 
Example 10
Source File: Arja_0097_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Gets a date formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date formatter
 * @throws IllegalArgumentException if the Locale has no date
 *  pattern defined
 */
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }

    if (locale != null) {
        key = new Pair(key, locale);
    }


    FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateInstanceCache.put(key, format);
            
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 11
Source File: JSpinnerDateEditor.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public JSpinnerDateEditor() {
	super(new SpinnerDateModel());
	dateFormatter = (SimpleDateFormat) DateFormat
			.getDateInstance(DateFormat.MEDIUM);
	((JSpinner.DateEditor) getEditor()).getTextField().addFocusListener(
			this);
	DateUtil dateUtil = new DateUtil();
	setMinSelectableDate(dateUtil.getMinSelectableDate());
	setMaxSelectableDate(dateUtil.getMaxSelectableDate());
	((JSpinner.DateEditor)getEditor()).getTextField().setFocusLostBehavior(JFormattedTextField.PERSIST);
	addChangeListener(this);
}
 
Example 12
Source File: BusinessGroupArchiver.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Save one group to xls file.
 * 
 * @param context
 * @param groupOwners
 * @param groupParticipants
 * @param groupWaiting
 * @param columnList
 * @param organisationalEntityList
 * @param orgEntityTitle
 * @param userLocale
 * @param fileNamePrefix
 * @param tempDir
 * @param charset
 * @return
 * @throws IOException
 */
private File archiveFileSingleGroup(final BGContext context, final List<Member> groupOwners, final List<Member> groupParticipants, final List<Member> groupWaiting,
        final List<String> columnList, final List<OrganisationalEntity> organisationalEntityList, final String orgEntityTitle, final Locale userLocale,
        String fileNamePrefix, final File tempDir, final String charset) throws IOException {
    File outFile = null;
    final StringBuffer stringBuffer = new StringBuffer();

    final Translator trans = getPackageTranslator(userLocale);
    final Translator propertyHandlerTranslator = userService.getUserPropertiesConfig().getTranslator(translator);
    // choice element has only one selected entry
    final List<String> titles = getCourseTitles(context);
    final Iterator<String> titleIterator = titles.iterator();
    final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, userLocale);
    final String formattedDate = dateFormat.format(new Date());

    // coursename
    stringBuffer.append(EOL);
    stringBuffer.append(trans.translate("archive.coursename"));
    stringBuffer.append(EOL);
    while (titleIterator.hasNext()) {
        stringBuffer.append(titleIterator.next());
    }
    stringBuffer.append(EOL);
    stringBuffer.append(EOL);

    // groupname
    stringBuffer.append(trans.translate("group.name"));
    stringBuffer.append(EOL);
    stringBuffer.append(fileNamePrefix);
    stringBuffer.append(EOL);
    stringBuffer.append(EOL);

    // date
    stringBuffer.append(trans.translate("archive.date"));
    stringBuffer.append(EOL);
    stringBuffer.append(formattedDate);
    stringBuffer.append(EOL);

    // members
    if (groupOwners.size() > 0) {
        appendSection(stringBuffer, trans.translate("archive.header.owners"), groupOwners, columnList, new ArrayList<OrganisationalEntity>(), "",
                propertyHandlerTranslator, OWNER);
    }
    if (groupParticipants.size() > 0) {
        appendSection(stringBuffer, trans.translate("archive.header.partipiciant"), groupParticipants, columnList, new ArrayList<OrganisationalEntity>(), "",
                propertyHandlerTranslator, PARTICIPANT);
    }
    if (groupWaiting.size() > 0) {
        appendSection(stringBuffer, trans.translate("archive.header.waitinggroup"), groupWaiting, columnList, new ArrayList<OrganisationalEntity>(), "",
                propertyHandlerTranslator, WAITING);
    }
    // appendInternInfo(stringBuffer, contextName, userLocale);
    // prefix must be at least 3 chars
    // add two of _ more if this is not the case
    fileNamePrefix = fileNamePrefix + "_";
    fileNamePrefix = fileNamePrefix.length() >= 3 ? fileNamePrefix : fileNamePrefix + "__";
    fileNamePrefix = fileNamePrefix.replaceAll("[*?\"<>/\\\\:]", "_"); // nicht erlaubte Zeichen in Dateinamen
    final String[] search = new String[] { "ß", "ä", "ö", "ü", "Ä", "Ö", "Ü", " " };
    final String[] replace = new String[] { "ss", "ae", "oe", "ue", "Ae", "Oe", "Ue", "_" };
    for (int i = 0; i < search.length; i++) {
        fileNamePrefix = fileNamePrefix.replaceAll(search[i], replace[i]);
    }
    outFile = File.createTempFile(fileNamePrefix, ".xls", tempDir);
    FileUtils.save(outFile, stringBuffer.toString(), charset);
    // FileUtils.saveString(outFile, stringBuffer.toString());
    String outFileName = outFile.getName();
    outFileName = outFileName.substring(0, outFileName.lastIndexOf("_"));
    outFileName += ".xls";
    final File renamedFile = new File(outFile.getParentFile(), outFileName);
    final boolean succesfullyRenamed = outFile.renameTo(renamedFile);
    if (succesfullyRenamed) {
        outFile = renamedFile;
    }

    return outFile;
}
 
Example 13
Source File: TaxiiConnectionConfig.java    From metron with Apache License 2.0 4 votes vote down vote up
public void setBeginTime(String beginTime) throws ParseException {
  SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.MEDIUM);
  this.beginTime = sdf.parse(beginTime);
}
 
Example 14
Source File: DatePicker.java    From microba with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private DateFormat dateFormatFromStyle(int dateStyle) {
	DateFormat df = DateFormat.getDateInstance(dateStyle, this.getLocale());
	df.setTimeZone(this.getZone());
	return df;
}
 
Example 15
Source File: RequestDialog.java    From jplag with GNU General Public License v3.0 4 votes vote down vote up
public static String formatCalendar(Calendar cal) {
	if(cal==null) return "No date";
	DateFormat df=DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.GERMAN);
	return df.format(cal.getTime());
}
 
Example 16
Source File: StockPriceHistoryBatcher.java    From training with MIT License 4 votes vote down vote up
/**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException {
//    	System.out.println(Runtime.getRuntime().freeMemory());
//    	long t0=System.currentTimeMillis();
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
        Date startDate;
        Date endDate;
        int save = 100;

        numStocks = (args.length < 1) ? 10000 : Integer.parseInt(args[0]);
        if (args.length < 2) {
            startDate = df.parse("01/01/12");
            endDate = df.parse("12/31/12");
        } else {
            startDate = df.parse(args[1]);
            endDate = df.parse(args[2]);
        }
        if (args.length < 3) {
            mode = 0;
        } 
        else {
            mode = Integer.parseInt(args[3]);
        }
        if (args.length > 4) {
            save = Integer.parseInt(args[4]);
        }
//        System.out.println("Num stocks " + numStocks + " " + startDate + " " + endDate);

        Random rand = new Random();
        initEM();
        StockPriceHistory[] saved = new StockPriceHistory[save];
        for (int i = 0; i < numStocks; i++) {
            String symbol = StockPriceUtils.makeSymbol(i);
            StockPriceHistory sph;
            if (mode == 0) {
                sph = new StockPriceHistoryImpl(symbol, startDate, endDate, em);
            } else {
                sph = new StockPriceHistoryLogger(symbol, startDate,
                              endDate, em);
            }
//            System.out.println("For " + sph.getSymbol()
//                + ": High " + nf.format(sph.getHighPrice())
//                + ", Low " + nf.format(sph.getLowPrice())
//                + ", Standard Deviation: " + sph.getStdDev().doubleValue());
            if (save > 0) {
//                saved[i % save] = sph;
                saved[rand.nextInt(save)] = sph;
            }
        }
//        System.out.println("Total time: " + (System.currentTimeMillis() - t0) + " ms");
    }
 
Example 17
Source File: TimeService.java    From jolie with GNU Lesser General Public License v2.1 4 votes vote down vote up
public TimeService() {
	dateFormat = DateFormat.getDateInstance( DateFormat.SHORT );
	dateTimeFormat = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.MEDIUM );
}
 
Example 18
Source File: Bug4994312.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) {
  SimpleDateFormat df = (SimpleDateFormat)
    DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.GERMAN);
  df.applyLocalizedPattern("tt.MM.uuuu");
  System.out.println(df.format(new Date()));
}
 
Example 19
Source File: Bug4994312.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) {
  SimpleDateFormat df = (SimpleDateFormat)
    DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.GERMAN);
  df.applyLocalizedPattern("tt.MM.uuuu");
  System.out.println(df.format(new Date()));
}
 
Example 20
Source File: Bug4994312.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) {
  SimpleDateFormat df = (SimpleDateFormat)
    DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.GERMAN);
  df.applyLocalizedPattern("tt.MM.uuuu");
  System.out.println(df.format(new Date()));
}