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

The following are Jave code examples for showing how to use getDateTimeInstance() of the java.text.DateFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: openjdk-jdk10   File: Bug4395196.java   Source Code and License Vote up 6 votes
public static void main(String[] arg)
        {
                int result = 0;
                Locale loc = new Locale("ko","KR");
                Date now = new Date(108, Calendar.APRIL, 9);

                DateFormat df =
                   DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,loc);
                SimpleDateFormat sdf = new SimpleDateFormat("",loc);
                sdf.applyPattern("yyyy. M. d a h:mm");
                if( !sdf.format(now).equals(df.format(now))){
                 result++;
                 System.out.println("error at " + sdf.format(now));
                 }
                df =  DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,loc);
                sdf.applyPattern("yyyy'\ub144' M'\uc6d4' d'\uc77c' '('EE')' a h:mm:ss");
                if( !sdf.format(now).equals(df.format(now))){
                 result++;
                 System.out.println("error at " + sdf.format(now));
                 }
                df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG,loc);
                sdf.applyPattern("yyyy. M. d a h'\uc2dc' mm'\ubd84' ss'\ucd08'");
                if( !sdf.format(now).equals(df.format(now))){
                 result++;
                 System.out.println("error at " + sdf.format(now));
                 }
                df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL,loc);
                sdf.applyPattern("yy. M. d a h'\uc2dc' mm'\ubd84' ss'\ucd08' z");
                if( !sdf.format(now).equals(df.format(now))){
                 result++;
                 System.out.println("error at " + sdf.format(now));
                 }

           if(result > 0) throw new RuntimeException();
}
 
Example 2
Project: TPlayer   File: CrashHandler.java   Source Code and License Vote up 6 votes
private String getCrashReport(Throwable ex) {
        StringBuffer exceptionStr = new StringBuffer();
//        String mtype = android.os.Build.MODEL; // 手机型号
//        String mtyb= android.os.Build.BRAND;//手机品牌
//        String cpuAbi = android.os.Build.CPU_ABI;//cpu架构
//        String sdk = android.os.Build.VERSION.SDK;//sdk版本号
//        String release = android.os.Build.VERSION.RELEASE;//依赖的系统版本号
//        String device = android.os.Build.DEVICE;//设备
//        String manufacturer = android.os.Build.MANUFACTURER;//手机品牌
        exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE
                + "(" + android.os.Build.MODEL + ")\n");

        Date date = new Date();
        DateFormat format = DateFormat
                .getDateTimeInstance();
        String t = format.format(date);
        exceptionStr.append("time: " + t + "\n");

        exceptionStr.append("Exception: " + ex.getMessage() + "\n");
        StackTraceElement[] elements = ex.getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            exceptionStr.append(elements[i].toString() + "\n");
        }
        return exceptionStr.toString();
    }
 
Example 3
Project: GitHub   File: NoteActivity.java   Source Code and License Vote up 6 votes
private void addNote() {
    String noteText = editText.getText().toString();
    editText.setText("");

    final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    String comment = "Added on " + df.format(new Date());

    Note note = new Note();
    note.setText(noteText);
    note.setComment(comment);
    note.setDate(new Date());
    note.setType(NoteType.TEXT);
    noteDao.insert(note);
    Log.d("DaoExample", "Inserted new note, ID: " + note.getId());

    updateNotes();
}
 
Example 4
Project: pgsqlblocks   File: UIAppender.java   Source Code and License Vote up 6 votes
@Override
public void append(LoggingEvent event) {
    boolean displayIsFine = display == null || display.isDisposed();
    boolean parentIsFine = parent == null || parent.isDisposed();
    if(displayIsFine || parentIsFine || text == null) {
        return;
    }
    DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, locale);
    Date time = new Date(event.getTimeStamp());
    String dateTime = dateTimeFormat.format(time);
    String excMessage;
    Object message = event.getMessage();
    if (message instanceof String) {
        excMessage = (String) message;
    } else {
        return;
    }
    final String logMessage = String.format("[%s] %s%n", dateTime, excMessage);
    parent.getDisplay().asyncExec(() -> {
        if (!text.isDisposed()) {
            text.append(logMessage);
        }
    });
}
 
Example 5
Project: scanning   File: StatusQueueView.java   Source Code and License Vote up 6 votes
private void rerun(StatusBean bean) {

		try {
			final DateFormat format = DateFormat.getDateTimeInstance();
			boolean ok = MessageDialog.openQuestion(getViewSite().getShell(), "Confirm resubmission "+bean.getName(),
					  "Are you sure you want to rerun "+bean.getName()+" submitted on "+format.format(new Date(bean.getSubmissionTime()))+"?");

			if (!ok) return;

			final StatusBean copy = bean.getClass().newInstance();
			copy.merge(bean);
			copy.setUniqueId(UUID.randomUUID().toString());
			copy.setMessage("Rerun of "+bean.getName());
			copy.setStatus(org.eclipse.scanning.api.event.status.Status.SUBMITTED);
			copy.setPercentComplete(0.0);
			copy.setSubmissionTime(System.currentTimeMillis());

			queueConnection.submit(copy, true);

			reconnect();

		} catch (Exception e) {
			ErrorDialog.openError(getViewSite().getShell(), "Cannot rerun "+bean.getName(), "Cannot rerun "+bean.getName()+"\n\nPlease contact your support representative.",
					new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
		}
	}
 
Example 6
Project: monarch   File: PerfQuery.java   Source Code and License Vote up 6 votes
public void run() throws Exception {
  Date startTime = new Date();
  setUp();
  DateFormat formatter = DateFormat.getDateTimeInstance();
  System.out.println("Test started at: " + formatter.format(startTime));
  runQueries();
  printSummary();
  tearDown();
  Date endTime = new Date();
  System.out.println("Test ended at: " + formatter.format(endTime));
  long durationMs = endTime.getTime() - startTime.getTime();
  long durationS = durationMs / 1000;
  long durationM = durationS / 60;
  long durationMM = durationM % 60;
  long durationH = durationM / 60;
  System.out.println("Test took " + durationH + "hrs, " + durationMM + "min.");
}
 
Example 7
Project: lams   File: FastDateFormat.java   Source Code and License Vote up 5 votes
/**
 * <p>Gets a date/time formatter instance using the specified style,
 * time zone and locale.</p>
 * 
 * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeStyle  time 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/time formatter
 * @throws IllegalArgumentException if the Locale has no date/time
 *  pattern defined
 */
public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone,
        Locale locale) {

    Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    key = new Pair(key, locale);

    FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key);
    if (format == null) {
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle,
                    locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateTimeInstanceCache.put(key, format);

        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date time pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 8
Project: microbit   File: AudioRecorderActivity.java   Source Code and License Vote up 5 votes
public File getAudioFilename() {
    // Get the directory for the user's public pictures directory.
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
    if(!dir.exists()) {
        if(!dir.mkdirs()) {
            Log.e(TAG, "Failed to create directory");
        }
    }

    Calendar c = Calendar.getInstance();
    DateFormat sdf = DateFormat.getDateTimeInstance();
    String filename = "voice_" + sdf.format(c.getTime());

    return new File(dir, filename + ".3gp");
}
 
Example 9
Project: weex-3d-map   File: HistoryManager.java   Source Code and License Vote up 5 votes
/**
 * <p>Builds a text representation of the scanning history. Each scan is encoded on one
 * line, terminated by a line break (\r\n). The values in each line are comma-separated,
 * and double-quoted. Double-quotes within values are escaped with a sequence of two
 * double-quotes. The fields output are:</p>
 *
 * <ol>
 *  <li>Raw text</li>
 *  <li>Display text</li>
 *  <li>Format (e.g. QR_CODE)</li>
 *  <li>Unix timestamp (milliseconds since the epoch)</li>
 *  <li>Formatted version of timestamp</li>
 *  <li>Supplemental info (e.g. price info for a product barcode)</li>
 * </ol>
 */
CharSequence buildHistory() {
  SQLiteOpenHelper helper = new DBHelper(activity);
  SQLiteDatabase db = null;
  Cursor cursor = null;
  try {
    db = helper.getWritableDatabase();
    cursor = db.query(DBHelper.TABLE_NAME,
                      COLUMNS,
                      null, null, null, null,
                      DBHelper.TIMESTAMP_COL + " DESC");

    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    StringBuilder historyText = new StringBuilder(1000);
    while (cursor.moveToNext()) {

      historyText.append('"').append(massageHistoryField(cursor.getString(0))).append("\",");
      historyText.append('"').append(massageHistoryField(cursor.getString(1))).append("\",");
      historyText.append('"').append(massageHistoryField(cursor.getString(2))).append("\",");
      historyText.append('"').append(massageHistoryField(cursor.getString(3))).append("\",");

      // Add timestamp again, formatted
      long timestamp = cursor.getLong(3);
      historyText.append('"').append(massageHistoryField(
          format.format(new Date(timestamp)))).append("\",");

      // Above we're preserving the old ordering of columns which had formatted data in position 5

      historyText.append('"').append(massageHistoryField(cursor.getString(4))).append("\"\r\n");
    }
    return historyText;
  } finally {
    close(cursor, db);
  }
}
 
Example 10
Project: WifiChatSharing   File: FileChooser.java   Source Code and License Vote up 5 votes
private void fill(File f) {
    File[]dirs = f.listFiles();
    this.setTitle("Current Dir: "+f.getName());
    List<Item>dir = new ArrayList<>();
    List<Item>fls = new ArrayList<>();
    try{
        for(File ff: dirs) {
            Date lastModDate = new Date(ff.lastModified());
            DateFormat formater = DateFormat.getDateTimeInstance();
            String date_modify = formater.format(lastModDate);
            if(ff.isDirectory()){
                File[] fbuf = ff.listFiles();
                int buf = 0;
                if(fbuf != null){
                    buf = fbuf.length;
                }
                else buf = 0;
                String num_item = String.valueOf(buf);
                if(buf == 0) num_item = num_item + " item";
                else num_item = num_item + " items";

                dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon"));
            }
            else {
                fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
            }
        }
    }catch(Exception e) {
        System.out.println(e.toString());
    }

    Collections.sort(dir);
    Collections.sort(fls);
    dir.addAll(fls);
    if(!f.getName().equalsIgnoreCase("sdcard"))
        dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
    adapter = new FileArrayAdapter(FileChooser.this, R.layout.activity_file_chooser,dir);
    this.setListAdapter(adapter);
}
 
Example 11
Project: Tusky   File: StatusDetailedViewHolder.java   Source Code and License Vote up 5 votes
@Override
protected void setCreatedAt(@Nullable Date createdAt) {
    if (createdAt != null) {
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT);
        timestampInfo.setText(dateFormat.format(createdAt));
    } else {
        timestampInfo.setText("");
    }
}
 
Example 12
Project: grammaticus   File: GrammaticalLocalizerTest.java   Source Code and License Vote up 5 votes
public void testDoParseDate_Exception_WrongFormat() {
    DateFormat df = DateFormat.getDateTimeInstance();
    try {
        BaseLocalizer.doParseDate("8 30, 1988 11:25:59 AM", df);
        fail("This should not happen!");
    }
    catch (ParseException expected) {}
}
 
Example 13
Project: neoscada   File: MonitorsLabelProvider.java   Source Code and License Vote up 5 votes
public MonitorsLabelProvider ( final IObservableMap... attributeMaps )
{
    super ();

    for ( int i = 0; i < attributeMaps.length; i++ )
    {
        attributeMaps[i].addMapChangeListener ( this.mapChangeListener );
    }
    this.attributeMaps = attributeMaps;

    this.dateFormat = DateFormat.getDateTimeInstance ( DateFormat.LONG, DateFormat.LONG );
}
 
Example 14
Project: logistimo-web-service   File: LocalDateUtil.java   Source Code and License Vote up 5 votes
public static Date parse(String timestampStr, Locale locale, String timezone)
    throws ParseException {
  DateFormat dateFormat = null;
  if (locale != null) {
    dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
  } else {
    dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
  }
  if (timezone != null) {
    dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
  }
  return dateFormat.parse(timestampStr);
}
 
Example 15
Project: jspoon   File: AdvancedTest.java   Source Code and License Vote up 5 votes
@Test
public void advancedTest2() throws Exception {
    HtmlAdapter<PageListWithoutAnnotation> htmlAdapter = jspoon.adapter(PageListWithoutAnnotation.class);
    PageListWithoutAnnotation page = htmlAdapter.fromHtml(HTML_CONTENT);

    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, CUSTOM_DEFAULT_LOCALE);

    List<AnnotatedPost> posts = new ArrayList<>();
    posts.add(new AnnotatedPost(dateFormat.parse("Apr 11, 2017 11:20:00 AM"), "Header1", "Content1", "Tag1", "Tag3", "Tag4"));
    posts.add(new AnnotatedPost(dateFormat.parse("Apr 9, 2017 11:10:00 AM"), "Header2", "Content2", "Tag2", "Tag3", "Tag5"));
    posts.add(new AnnotatedPost(dateFormat.parse("Apr 1, 2017 9:37:00 PM"), "Header3", "Content3", "Tag1", "Tag4", "Tag7"));

    assertEquals(page.quote, "Blah, blah.");
    assertEquals(page.posts, posts);
}
 
Example 16
Project: lams   File: DefaultDateTypeAdapter.java   Source Code and License Vote up 4 votes
public DefaultDateTypeAdapter(int dateStyle, int timeStyle) {
  this(DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US),
      DateFormat.getDateTimeInstance(dateStyle, timeStyle));
}
 
Example 17
Project: logistimo-web-service   File: LocalDateUtil.java   Source Code and License Vote up 4 votes
public static String format(String strTimestamp, Locale locale, String timezone)
    throws ParseException {
  // Convert to Date object
  DateFormat df = DateFormat.getDateTimeInstance();
  return format(df.parse(strTimestamp), locale, timezone);
}
 
Example 18
Project: BittrexApi   File: DefaultDateTypeAdapter.java   Source Code and License Vote up 4 votes
@SuppressLint("SimpleDateFormat")
public DefaultDateTypeAdapter(Class<? extends Date> dateType, int dateStyle, int timeStyle) {
    this(dateType,
            DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US),
            DateFormat.getDateTimeInstance(dateStyle, timeStyle));
}
 
Example 19
Project: letv   File: DefaultDateTypeAdapter.java   Source Code and License Vote up 4 votes
public DefaultDateTypeAdapter(int dateStyle, int timeStyle) {
    this(DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.US), DateFormat.getDateTimeInstance(dateStyle, timeStyle));
}
 
Example 20
Project: OpenJSharp   File: Date.java   Source Code and License Vote up 2 votes
/**
 * Creates a string representation of this <tt>Date</tt> object in an
 * implementation-dependent form. The intent is that the form should
 * be familiar to the user of the Java application, wherever it may
 * happen to be running. The intent is comparable to that of the
 * "<code>%c</code>" format supported by the <code>strftime()</code>
 * function of ISO&nbsp;C.
 *
 * @return  a string representation of this date, using the locale
 *          conventions.
 * @see     java.text.DateFormat
 * @see     java.util.Date#toString()
 * @see     java.util.Date#toGMTString()
 * @deprecated As of JDK version 1.1,
 * replaced by <code>DateFormat.format(Date date)</code>.
 */
@Deprecated
public String toLocaleString() {
    DateFormat formatter = DateFormat.getDateTimeInstance();
    return formatter.format(this);
}