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

The following examples show how to use java.text.DateFormat#getTimeInstance() . 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: DateTimePicker.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private JPanel createTimePanel() {
    JPanel newPanel = new JPanel();
    newPanel.setLayout(new FlowLayout());
    Date date = getDate();
    if (date == null) {
        Calendar calendar = Calendar.getInstance(timeZone);
        date = calendar.getTime();
    }
    SpinnerDateModel dateModel = new SpinnerDateModel(date, null, null, Calendar.DAY_OF_MONTH);
    timeSpinner = new JSpinner(dateModel);
    if (timeFormat == null) {
        timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
    }
    updateTextFieldFormat();
    newPanel.add(new JLabel("Time:"));
    newPanel.add(timeSpinner);
    newPanel.setBackground(Color.WHITE);
    return newPanel;
}
 
Example 2
Source File: DateFormatConverter.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public static String getJavaTimePattern(int style, Locale locale) {
   	DateFormat df = DateFormat.getTimeInstance(style, locale);
   	if( df instanceof SimpleDateFormat ) {
   		return ((SimpleDateFormat)df).toPattern();
   	} else {
   		switch( style ) {
   		case DateFormat.SHORT:
   			return "h:mm a";
   		case DateFormat.MEDIUM:
   			return "h:mm:ss a";
   		case DateFormat.LONG:
   			return "h:mm:ss a";
   		case DateFormat.FULL:
   			return "h:mm:ss a";
   		default:
   			return "h:mm:ss a";
   		}
   	}
}
 
Example 3
Source File: DateTimeParser.java    From yamlbeans with MIT License 5 votes vote down vote up
public SimpleParser (int dateType, int timeType) {
	if (timeType < 0) {
		this.format = DateFormat.getDateInstance(dateType);
	} else if (dateType < 0) {
		this.format = DateFormat.getTimeInstance(timeType);
	} else {
		this.format = DateFormat.getDateTimeInstance(dateType, timeType);
	}
}
 
Example 4
Source File: TCKLocalizedPrinterParser.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test(dataProvider="time")
public void test_time_parse(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) {
    DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale);
    Date oldDate = new Date(1970, 0, 0, time.getHour(), time.getMinute(), time.getSecond());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale);
    TemporalAccessor parsed = f.parse(text, pos);
    assertEquals(pos.getIndex(), text.length());
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(LocalTime.from(parsed), time);
}
 
Example 5
Source File: DateFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.text.DateFormat#getTimeInstance()
 */
public void test_getTimeInstance() {
	SimpleDateFormat f2 = (SimpleDateFormat) DateFormat.getTimeInstance();
	assertTrue("Wrong class", f2.getClass() == SimpleDateFormat.class);
	assertTrue("Wrong default", f2.equals(DateFormat.getTimeInstance(
			DateFormat.DEFAULT, Locale.getDefault())));
	assertTrue("Wrong symbols", f2.getDateFormatSymbols().equals(
			new DateFormatSymbols()));
	assertTrue("Doesn't work",
			f2.format(new Date()).getClass() == String.class);
}
 
Example 6
Source File: 1_FastDateFormat.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(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) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);
        
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 7
Source File: TCKLocalizedPrinterParser.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test(dataProvider="time")
public void test_time_parse(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) {
    DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale);
    Date oldDate = new Date(1970, 0, 0, time.getHour(), time.getMinute(), time.getSecond());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale);
    TemporalAccessor parsed = f.parse(text, pos);
    assertEquals(pos.getIndex(), text.length());
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(LocalTime.from(parsed), time);
}
 
Example 8
Source File: Lang_50_FastDateFormat_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(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) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);
        
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 9
Source File: FastDateFormat.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(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) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);
        
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 10
Source File: TCKLocalizedPrinterParser.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test(dataProvider="time")
public void test_time_print(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) {
    DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale);
    Date oldDate = new Date(1970, 0, 0, time.getHour(), time.getMinute(), time.getSecond());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale);
    String formatted = f.format(time);
    assertEquals(formatted, text);
}
 
Example 11
Source File: UserTimeServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public String timeFormat(Date time, Locale locale, int df) {
    if (time == null || locale == null) return "";
    log.debug("timeFormat: {}, {}, {}", time.toString(), locale.toString(), df);

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

    FastDateFormat format = cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);
        
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 13
Source File: TimeFormatUtil.java    From zap-android with MIT License 5 votes vote down vote up
/**
 * Returns a nicely formatted time.
 *
 * @param time    in seconds
 * @param context
 * @return
 */
public static String formatTimeAndDateLong(long time, Context context) {
    DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, context.getResources().getConfiguration().locale);
    String formattedDate = df.format(new Date(time * 1000L));
    DateFormat tf = DateFormat.getTimeInstance(DateFormat.MEDIUM, context.getResources().getConfiguration().locale);
    String formattedTime = tf.format(new Date(time * 1000L));
    return (formattedDate + ", " + formattedTime);
}
 
Example 14
Source File: Arja_0071_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(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) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);
        
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 15
Source File: MessageDisplay.java    From xltsearch with Apache License 2.0 5 votes vote down vote up
@FXML
private void initialize() {
    // replaces CONSTRAINED_RESIZE_POLICY
    summaryCol.prefWidthProperty().bind(
        table.widthProperty()
        .subtract(timeCol.widthProperty())
        .subtract(levelCol.widthProperty())
        .subtract(fromCol.widthProperty())
    );

    table.itemsProperty().bind(MessageLogger.messagesProperty());

    final DateFormat df = DateFormat.getTimeInstance();
    timeCol.setCellValueFactory((r) ->
        new ReadOnlyStringWrapper(df.format(new Date(r.getValue().timestamp))));
    levelCol.setCellValueFactory((r) ->
        new ReadOnlyStringWrapper(r.getValue().level.toString()));
    fromCol.setCellValueFactory((r) ->
        new ReadOnlyStringWrapper(r.getValue().from));
    summaryCol.setCellValueFactory((r) ->
        new ReadOnlyStringWrapper(r.getValue().summary));

    table.getSelectionModel().selectedItemProperty().addListener((o, oldValue, newValue) -> {
        if (newValue != null) {
            detailsField.setText(newValue.summary + '\n' + newValue.details);
        } else {
            detailsField.setText("");
        }
    });

    logLevel.getItems().setAll(Message.Level.values());
    logLevel.getSelectionModel().select(MessageLogger.logLevelProperty().get());
    logLevel.getSelectionModel().selectedItemProperty().addListener(
        (o, oldValue, newValue) -> MessageLogger.logLevelProperty().set(newValue));
}
 
Example 16
Source File: FormatCache.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) {
    final 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();
            final 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 (final ClassCastException ex) {
            throw new IllegalArgumentException("No date time pattern for locale: " + locale);
        }
    }
    return pattern;
}
 
Example 17
Source File: MessageFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_setFormats$Ljava_text_Format() throws Exception {
  MessageFormat f1 = (MessageFormat) format1.clone();

  // case 1: Test with repeating formats and max argument index < max
  // offset
  // compare getFormats() results after calls to setFormats(Format[])
  Format[] correctFormats = new Format[] {
    DateFormat.getTimeInstance(),
    new ChoiceFormat("0#off|1#on"),
    DateFormat.getTimeInstance(),
    NumberFormat.getCurrencyInstance(),
    new ChoiceFormat("1#few|2#ok|3#a lot")
  };

  f1.setFormats(correctFormats);
  Format[] formats = f1.getFormats();

  assertTrue("Test1A:Returned wrong number of formats:", correctFormats.length <= formats.length);
  for (int i = 0; i < correctFormats.length; i++) {
    assertEquals("Test1B:wrong format for argument index " + i + ":", correctFormats[i], formats[i]);
  }

  // case 2: Try to pass null argument to setFormats().
  try {
    f1.setFormats(null);
    fail();
  } catch (NullPointerException expected) {
  }
}
 
Example 18
Source File: DateUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Equivalent of <LAMS:Date value="value" type="date|time|both"/>. Use for processing a date to send to the client
    * via JSON. Locale comes from request.getLocale();
    *
    * @param value
    * @param type
    *            TYPE_BOTH (both data and time), TYPE_DATE or TYPE_TIME
    * @param locale
    * @return
    */
   public static String convertToStringForJSON(Date value, Integer style, Integer type, Locale locale) {

HttpSession ss = SessionManager.getSession();
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
TimeZone tz = user.getTimeZone();

int dateStyle, timeStyle;
switch (style) {
    case DateFormat.SHORT:
	dateStyle = DateFormat.SHORT;
	timeStyle = DateFormat.SHORT;
	break;
    case DateFormat.FULL:
	dateStyle = DateFormat.LONG;
	timeStyle = DateFormat.FULL;
	break;
    default:
	dateStyle = DateFormat.LONG;
	timeStyle = DateFormat.MEDIUM;
}

DateFormat df = null;
switch (type) {
    case TYPE_DATE:
	df = DateFormat.getDateInstance(dateStyle, locale);
	break;
    case TYPE_TIME:
	df = DateFormat.getTimeInstance(timeStyle, locale);
	break;
    default:
	df = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
}

if (tz != null) {
    df.setTimeZone(tz);
}

return df.format(value);
   }
 
Example 19
Source File: FormatRenderer.java    From DiskBrowser with GNU General Public License v3.0 4 votes vote down vote up
public static FormatRenderer getTimeRenderer ()
// ---------------------------------------------------------------------------------//
{
  return new FormatRenderer (DateFormat.getTimeInstance ());
}
 
Example 20
Source File: DateTimePickerTag.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
private void writePickerHtml(Writer out) throws IOException {

        HtmlTag group = new HtmlTag("div");
        group.setAttribute("class", "input-group");
        group.setAttribute("id", data.getName() + "_datepicker_widget");

        if (!data.getDisableDate()) {
            HtmlTag dateAddon = createInputAddonTag("date", "header-calendar");
            group.addBody(dateAddon);

            SimpleDateFormat dateFmt = (SimpleDateFormat)
                    DateFormat.getDateInstance(DateFormat.SHORT, data.getLocale());

            HtmlTag dateInput = new HtmlTag("input");
            dateInput.setAttribute("id", data.getName() + "_datepicker_widget_input");
            dateInput.setAttribute("data-provide", "date-picker");
            dateInput.setAttribute("data-date-today-highlight", "true");
            dateInput.setAttribute("data-date-orientation", "top auto");
            dateInput.setAttribute("data-date-autoclose", "true");
            dateInput.setAttribute("data-date-language", data.getLocale().toString());
            dateInput.setAttribute("data-date-format",
                    toDatepickerFormat(dateFmt.toPattern()));
            dateInput.setAttribute("type", "text");
            dateInput.setAttribute("class", "form-control");
            dateInput.setAttribute("id", data.getName() + "_datepicker_widget_input");
            dateInput.setAttribute("size", "15");

            dateInput.setAttribute("data-picker-name", data.getName());
            dateInput.setAttribute("data-initial-year", String.valueOf(data.getYear()));
            dateInput.setAttribute("data-initial-month", String.valueOf(data.getMonth()));
            dateInput.setAttribute("data-initial-day", String.valueOf(data.getDay()));

            String firstDay = getJavascriptPickerDayIndex(
                    data.getCalendar().getFirstDayOfWeek());
            dateInput.setAttribute("data-date-week-start", firstDay);

            group.addBody(dateInput);
        }

        if (!data.getDisableTime()) {
            HtmlTag timeAddon = createInputAddonTag("time", "header-clock");
            group.addBody(timeAddon);

            SimpleDateFormat timeFmt = (SimpleDateFormat)
                    DateFormat.getTimeInstance(DateFormat.SHORT, data.getLocale());

            HtmlTag timeInput = new HtmlTag("input");
            timeInput.setAttribute("type", "text");
            timeInput.setAttribute("data-provide", "time-picker");
            timeInput.setAttribute("class", "form-control");
            timeInput.setAttribute("data-time-format",
                                         toPhpTimeFormat(timeFmt.toPattern()));
            timeInput.setAttribute("id", data.getName() + "_timepicker_widget_input");
            timeInput.setAttribute("size", "10");

            timeInput.setAttribute("data-picker-name", data.getName());
            timeInput.setAttribute("data-initial-hour",
                    String.valueOf(data.getHourOfDay()));
            timeInput.setAttribute("data-initial-minute", String.valueOf(data.getMinute()));

            group.addBody(timeInput);
        }

        HtmlTag tzAddon = new HtmlTag("span");
        tzAddon.setAttribute("id", data.getName() + "_tz_input_addon");
        tzAddon.setAttribute("data-picker-name", data.getName());
        tzAddon.setAttribute("class", "input-group-addon text tz_input_addon");

        DateFormat tzFmt = new SimpleDateFormat("z", data.getLocale());
        tzFmt.setTimeZone(data.getCalendar().getTimeZone());
        tzAddon.addBody(tzFmt.format(data.getDate()));

        group.addBody(tzAddon);
        out.append(group.render());

        // compatibility with the old struts form
        // these values are updated when the picker changes using javascript
        //
        // if you are tempted to not write out these fields in case
        // date or time are disabled for the picker, mind that
        // DatePicker::readMap resets the date to now() if not all fields
        // are present.
        out.append(createHiddenInput("day", String.valueOf(data.getDay())).render());
        out.append(createHiddenInput("month", String.valueOf(data.getMonth())).render());
        out.append(createHiddenInput("year", String.valueOf(data.getYear())).render());

        out.append(createHiddenInput("hour", String.valueOf(data.getHour())).render());
        out.append(createHiddenInput("minute", String.valueOf(data.getMinute())).render());
        if (data.isLatin()) {
            out.append(createHiddenInput("am_pm",
                    String.valueOf((data.getHour() > 12) ? 1 : 0)).render());
        }
    }