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

The following examples show how to use java.text.DateFormat#getDateTimeInstance() . These examples are extracted from open source projects. 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 Project: Time4A   File: SimpleFormatter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>Constructs a style-based formatter for plain timestamp objects. </p>
 *
 * @param   dateStyle   format style for the date component
 * @param   timeStyle   format style for the time component
 * @param   locale      format locale
 * @return  new {@code SimpleFormatter}-instance
 * @throws  IllegalStateException if no localized format pattern can be retrieved
 * @since   5.0
 */
/*[deutsch]
 * <p>Konstruiert einen Formatierer f&uuml;r einfache Zeitstempelobjekte. </p>
 *
 * @param   dateStyle   format style for the date component
 * @param   timeStyle   format style for the time component
 * @param   locale      format locale
 * @return  new {@code SimpleFormatter}-instance
 * @throws  IllegalStateException if no localized format pattern can be retrieved
 * @since   5.0
 */
public static SimpleFormatter<PlainTimestamp> ofTimestampStyle(
    DisplayMode dateStyle,
    DisplayMode timeStyle,
    Locale locale
) {

    DateFormat df = DateFormat.getDateTimeInstance(dateStyle.getStyleValue(), timeStyle.getStyleValue(), locale);
    String pattern = FormatUtils.removeZones(getFormatPattern(df));
    return SimpleFormatter.ofTimestampPattern(pattern, locale);

}
 
Example 2
public Component getTableCellRendererComponent(final JTable list,
                                               final Object value,
                                               final boolean isSelected,
                                               final boolean cellHasFocus,
                                               final int index,
                                               final int col) {
    super.getTableCellRendererComponent(list, value, isSelected, false,
                                        index, col);
    final File file = (File)fFileList.getValueAt(index, 0);
    setEnabled(isSelectableInList(file));
    final DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT);
    final Date date = (Date)value;

    if (date != null) {
        setText(formatter.format(date));
    } else {
        setText("");
    }

    return this;
}
 
Example 3
Source Project: journaldev   File: HomeController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
	logger.info("Welcome home! The client locale is {}.", locale);
	//adding some time lag to check interceptor execution
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	Date date = new Date();
	DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
	
	String formattedDate = dateFormat.format(date);
	
	model.addAttribute("serverTime", formattedDate );
	logger.info("Before returning view page");
	return "home";
}
 
Example 4
Source Project: hbase   File: HFilePrettyPrinter.java    License: Apache License 2.0 6 votes vote down vote up
private SimpleReporter(MetricRegistry registry,
                        PrintStream output,
                        Locale locale,
                        TimeZone timeZone,
                        TimeUnit rateUnit,
                        TimeUnit durationUnit,
                        MetricFilter filter) {
  super(registry, "simple-reporter", filter, rateUnit, durationUnit);
  this.output = output;
  this.locale = locale;

  this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,
      DateFormat.MEDIUM,
      locale);
  dateFormat.setTimeZone(timeZone);
}
 
Example 5
Source Project: olat   File: FolderComponent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Wraps the folder module as a component.
 * 
 * @param ureq
 *            The user request
 * @param name
 *            The component name
 * @param rootContainer
 *            The base container of this component
 * @param filter
 *            A file filter or NULL to not use a filter
 * @param customLinkTreeModel
 *            A custom link tree model used in the HTML editor or NULL to not use this feature.
 */
public FolderComponent(UserRequest ureq, String name, VFSContainer rootContainer, VFSItemFilter filter, CustomLinkTreeModel customLinkTreeModel, Long courseNodeId) {
    super(name);
    this.identityEnv = ureq.getUserSession().getIdentityEnvironment();
    this.filter = filter;
    this.customLinkTreeModel = customLinkTreeModel;
    this.courseNodeId = courseNodeId;
    exclFilter = new VFSItemExcludePrefixFilter(ATTACHMENT_EXCLUDE_PREFIXES);
    Locale locale = ureq.getLocale();
    collator = Collator.getInstance(locale);
    translator = PackageUtil.createPackageTranslator(FolderRunController.class, locale);
    sort(SORT_NAME);
    this.rootContainer = rootContainer;
    setCurrentContainerPath("/");

    dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
}
 
Example 6
Source Project: radar   File: CatMybatisPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private String getParameterValue(Object obj) {
	String value = null;
	if (obj instanceof String) {
		value = "'" + obj.toString() + "'";
	} else if (obj instanceof Date) {
		DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
		value = "'" + formatter.format(obj) + "'";
	} else {
		if (obj != null) {
			value = obj.toString();
		} else {
			value = "";
		}

	}
	return value;
}
 
Example 7
Source Project: journaldev   File: HomeController.java    License: MIT License 5 votes vote down vote up
/**
 * Simply selects the home view to render by returning its name.
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
	System.out.println("MyBean hashcode="+myBean.hashCode());
	System.out.println("MyAnnotatedBean hashcode="+myAnnotatedBean.hashCode());
	
	Date date = new Date();
	DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
	
	String formattedDate = dateFormat.format(date);
	
	model.addAttribute("serverTime", formattedDate );
	
	return "home";
}
 
Example 8
/**
 * Simply selects the home view to render by returning its name.
 * 
 * @param locale
 *            the locale
 * @param model
 *            the model
 * @return the string
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
	logger.info("Welcome home! the client locale is " + locale.toString());
	Date date = new Date();
	DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
			DateFormat.LONG, locale);
	String formattedDate = dateFormat.format(date);
	model.addAttribute("serverTime", formattedDate);
	return "redirect:/auth/login";
}
 
Example 9
Source Project: flow   File: StringToDateConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the format used by {@link #convertToPresentation(Date, ValueContext)}
 * and {@link #convertToModel(String, ValueContext)}.
 *
 * @param locale
 *            The locale to use
 * @return A DateFormat instance
 */
protected DateFormat getFormat(Locale locale) {
    if (locale == null) {
        locale = Locale.getDefault();
    }

    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
            DateFormat.MEDIUM, locale);
    format.setLenient(false);
    return format;
}
 
Example 10
Source Project: consulo   File: DateFormatUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static SyncDateFormat[] getDateTimeFormats() {
  DateFormat[] formats = new DateFormat[4];

  boolean loaded = false;
  try {
    if (SystemInfo.isWin7OrNewer) {
      loaded = getWindowsFormats(formats);
    }
    else if (SystemInfo.isMac) {
      loaded = getMacFormats(formats);
    }
    else if (SystemInfo.isUnix) {
      loaded = getUnixFormats(formats);
    }
  }
  catch (Throwable t) {
    LOG.info(t);
  }

  if (!loaded) {
    formats[0] = DateFormat.getDateInstance(DateFormat.SHORT);
    formats[1] = DateFormat.getTimeInstance(DateFormat.SHORT);
    formats[2] = DateFormat.getTimeInstance(DateFormat.MEDIUM);
    formats[3] = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
  }

  SyncDateFormat[] synced = new SyncDateFormat[4];
  for (int i = 0; i < formats.length; i++) {
    synced[i] = new SyncDateFormat(formats[i]);
  }
  return synced;
}
 
Example 11
public String getFormatTimeslotDateTime(SignupTimeslot timeslot){
	
	final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
	final char SEPARATOR = '-';
	StringBuilder sb = new StringBuilder();		
	sb.append(df.format(timeslot.getStartTime()));
	sb.append(SEPARATOR);
	sb.append(df.format(timeslot.getEndTime()));
	
	return sb.toString();		
}
 
Example 12
/**
 * Конструктор
 * @param source исходная страница - объект {@link SerializablePage}
 * @param localTime определяет, будет ли использоваться локальное время телефона (если true), или часовой пояс имиджборды (если false)
 * @param reduceNames если true, имена пользователя по умолчанию (напр. Аноним) не будут показываться
 * @param spanClickListener обработчик ссылок URL внутри постов, ссылок на другие посты, а также ссылок на e-mail (mailto)
 * @param imageGetter загрузчик картинок, содержащихся в тексте постов (например, смайлики)
 * @param theme текущая тема
 * @param floatingModels массив из двух моделей обтекания картинка текстом. Первый элемент - обычная 
 * превьюшка, второй - со строкой с дополнительной информацией о вложении (gif, видео, аудио). 
 * Допустимо значение null, если обтекание не нужно вообще.
 */
public PresentationModel(SerializablePage source, boolean localTime, boolean reduceNames,
        URLSpanClickListener spanClickListener, ImageGetter imageGetter, Theme theme, FloatingModel[] floatingModels) {
    if (source.pageModel.type == UrlPageModel.TYPE_OTHERPAGE) throw new IllegalArgumentException(); 
    this.source = source;
    this.spanClickListener = spanClickListener;
    this.imageGetter = imageGetter;
    this.theme = theme;
    this.floatingModels = floatingModels;
    this.reduceNames = reduceNames;
    Database database = MainApplication.getInstance().database;
    this.isHiddenDelegate = source.pageModel.type == UrlPageModel.TYPE_THREADPAGE ?
            database.getCachedIsHiddenDelegate(source.pageModel.chanName, source.pageModel.boardName, source.pageModel.threadNumber) :
            database.getDefaultIsHiddenDelegate();
    this.autohideRules = new ArrayList<AutohideActivity.CompiledAutohideRule>();
    try {
        JSONArray autohideJson = new JSONArray(MainApplication.getInstance().settings.getAutohideRulesJson());
        for (int i=0; i<autohideJson.length(); ++i) {
            AutohideActivity.AutohideRule rule = AutohideActivity.AutohideRule.fromJson(autohideJson.getJSONObject(i));
            if (rule.matches(source.pageModel.chanName, source.pageModel.boardName, source.pageModel.threadNumber)) {
                this.autohideRules.add(new AutohideActivity.CompiledAutohideRule(rule));
            }
        }
    } catch (Exception e) {
        Logger.e(TAG, "error while processing regex autohide rules", e);
    }
    AndroidDateFormat.initPattern();
    String datePattern = AndroidDateFormat.getPattern();
    DateFormat dateFormat = datePattern == null ?
            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) : new SimpleDateFormat(datePattern, Locale.US);
    dateFormat.setTimeZone(localTime ? TimeZone.getDefault() : TimeZone.getTimeZone(source.boardModel.timeZoneId));
    this.dateFormat = dateFormat;
    this.size = getSerializablePageSize(source);
}
 
Example 13
Source Project: uyuni   File: DatePicker.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void analyzeDateFormat() {
    // HACK: This checks whether the am/pm indicator is
    // in the default date format for this locale
    SimpleDateFormat sdf =
        (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                DateFormat.SHORT, locale);
    String pattern = sdf.toPattern();
    isLatin = (pattern.indexOf('a') >= 0);
    // HACK: check whether month or date comes first
    isDayBeforeMonth = pattern.indexOf('d') < pattern.indexOf('M');
}
 
Example 14
/** Return the current time and date as a string using a long format.
    The time and date is formatted using DateFormat.LONG and
    Locale.ENGLISH. */
public static String getDate()
{
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                                       DateFormat.LONG,
                                                       Locale.ENGLISH);
    Date date = Calendar.getInstance().getTime();
    return format.format(date);
}
 
Example 15
public static void main(String[] args) {
    DateFormat df1 = null; // 声明一个DateFormat
    DateFormat df2 = null; // 声明一个DateFormat
    df1 = DateFormat.getDateInstance(DateFormat.YEAR_FIELD, new Locale("zh", "CN")); // 得到日期的DateFormat对象
    df2 = DateFormat.getDateTimeInstance(DateFormat.YEAR_FIELD, DateFormat.ERA_FIELD,
        new Locale("zh", "CN")); // 得到日期时间的DateFormat对象
    System.out.println("DATE:" + df1.format(new Date())); // 按照日期格式化
    System.out.println("DATETIME:" + df2.format(new Date())); // 按照日期时间格式化
}
 
Example 16
private String dateformatter(double timestamp) {
    Date date = new Date((long) timestamp);
    DateFormat format = DateFormat.getDateTimeInstance();
    return format.format(date);
}
 
Example 17
Source Project: MiBandDecompiled   File: a.java    License: Apache License 2.0 4 votes vote down vote up
a()
{
    this(DateFormat.getDateTimeInstance(2, 2, Locale.US), DateFormat.getDateTimeInstance(2, 2));
}
 
Example 18
@Override
public DateFormat createDateFormat(String pattern, Locale locale, TimeZone tz)
{
	int[] dateStyle = null;
	int[] timeStyle = null;
	if (pattern != null && pattern.trim().length() > 0)
	{			
		int sepIdx = pattern.indexOf(STANDARD_DATE_FORMAT_SEPARATOR);
		String dateTok = sepIdx < 0 ? pattern : pattern.substring(0, sepIdx);
		dateStyle = getDateStyle(dateTok);
		if (dateStyle != null)
		{
			if (sepIdx >= 0)
			{
				String timeTok = pattern.substring(sepIdx + STANDARD_DATE_FORMAT_SEPARATOR.length());
				timeStyle = getDateStyle(timeTok);
			}
			else
			{
				timeStyle = dateStyle;
			}
		}
	}
	
	DateFormat format;
	if (dateStyle != null && timeStyle != null)
	{
		format = getDateFormat(dateStyle, timeStyle, locale);
	}
	else
	{			
		if (locale == null)
		{
			format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
		}
		else
		{
			format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
		}
		if (
			pattern != null && pattern.trim().length() > 0
			&& format instanceof SimpleDateFormat
			)
		{
			((SimpleDateFormat) format).applyPattern(pattern);
		}
	}
	
	if (tz != null)
	{
		format.setTimeZone(tz);
	}

	return format;
}
 
Example 19
Source Project: jdk8u60   File: FilePane.java    License: GNU General Public License v2.0 4 votes vote down vote up
DetailsTableCellRenderer(JFileChooser chooser) {
    this.chooser = chooser;
    df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
                                        chooser.getLocale());
}
 
Example 20
Source Project: reacteu-app   File: CaptureActivity.java    License: MIT License 4 votes vote down vote up
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
  statusView.setVisibility(View.GONE);
  viewfinderView.setVisibility(View.GONE);
  resultView.setVisibility(View.VISIBLE);

  ImageView barcodeImageView = (ImageView) findViewById(fakeR.getId("id", "barcode_image_view"));
  if (barcode == null) {
    barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
        fakeR.getId("drawable", "launcher_icon")));
  } else {
    barcodeImageView.setImageBitmap(barcode);
  }

  TextView formatTextView = (TextView) findViewById(fakeR.getId("id", "format_text_view"));
  formatTextView.setText(rawResult.getBarcodeFormat().toString());

  TextView typeTextView = (TextView) findViewById(fakeR.getId("id", "type_text_view"));
  typeTextView.setText(resultHandler.getType().toString());

  DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
  String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
  TextView timeTextView = (TextView) findViewById(fakeR.getId("id", "time_text_view"));
  timeTextView.setText(formattedTime);


  TextView metaTextView = (TextView) findViewById(fakeR.getId("id", "meta_text_view"));
  View metaTextViewLabel = findViewById(fakeR.getId("id", "meta_text_view_label"));
  metaTextView.setVisibility(View.GONE);
  metaTextViewLabel.setVisibility(View.GONE);
  Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
  if (metadata != null) {
    StringBuilder metadataText = new StringBuilder(20);
    for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
      if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
        metadataText.append(entry.getValue()).append('\n');
      }
    }
    if (metadataText.length() > 0) {
      metadataText.setLength(metadataText.length() - 1);
      metaTextView.setText(metadataText);
      metaTextView.setVisibility(View.VISIBLE);
      metaTextViewLabel.setVisibility(View.VISIBLE);
    }
  }

  TextView contentsTextView = (TextView) findViewById(fakeR.getId("id", "contents_text_view"));
  CharSequence displayContents = resultHandler.getDisplayContents();
  contentsTextView.setText(displayContents);
  // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
  int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
  contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

  TextView supplementTextView = (TextView) findViewById(fakeR.getId("id", "contents_supplement_text_view"));
  supplementTextView.setText("");
  supplementTextView.setOnClickListener(null);
  if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
      PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
    SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
                                                   resultHandler.getResult(),
                                                   historyManager,
                                                   this);
  }

  int buttonCount = resultHandler.getButtonCount();
  ViewGroup buttonView = (ViewGroup) findViewById(fakeR.getId("id", "result_button_view"));
  buttonView.requestFocus();
  for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
    TextView button = (TextView) buttonView.getChildAt(x);
    if (x < buttonCount) {
      button.setVisibility(View.VISIBLE);
      button.setText(resultHandler.getButtonText(x));
      button.setOnClickListener(new ResultButtonListener(resultHandler, x));
    } else {
      button.setVisibility(View.GONE);
    }
  }

  if (copyToClipboard && !resultHandler.areContentsSecure()) {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    if (displayContents != null) {
      clipboard.setText(displayContents);
    }
  }
}