public Array toSqlArray ( final Connection connection, final Event event ) throws SQLException { final DateFormat isoDateFormat = new SimpleDateFormat ( isoDatePatterrn ); final String[] fields; // array must be large enough to hold all attributes plus id and both time stamps fields = new String[ ( event.getAttributes ().size () + 3 ) * 2]; // now populate values fields[0] = "id"; fields[1] = event.getId ().toString (); fields[2] = "sourceTimestamp"; fields[3] = isoDateFormat.format ( event.getSourceTimestamp () ); fields[4] = "entryTimestamp"; fields[5] = isoDateFormat.format ( event.getEntryTimestamp () ); int i = 6; for ( final Entry<String, Variant> entry : event.getAttributes ().entrySet () ) { fields[i] = entry.getKey (); fields[i + 1] = entry.getValue ().toString (); i += 2; } return connection.createArrayOf ( "text", fields ); }
/** * Try to parse the given date as a HTTP date. */ public static final long parseDate(String value, DateFormat[] threadLocalformats) { Long cachedDate = parseCache.get(value); if (cachedDate != null) return cachedDate.longValue(); Long date = null; if (threadLocalformats != null) { date = internalParseDate(value, threadLocalformats); updateParseCache(value, date); } else { synchronized (parseCache) { date = internalParseDate(value, formats); updateParseCache(value, date); } } if (date == null) { return (-1L); } else { return date.longValue(); } }
@Override public PropBagEx getXml() { DateFormat dateFormatter = getDateFormatter(); PropBagEx xml = super.getXml(); xml.setNode("after", dateFormatter.format(afterDate)); xml.setNode("after/@selected", displayAfter); xml.setNode("until", dateFormatter.format(untilDate)); xml.setNode("until/@selected", displayUntil); xml.setNode("visible", visible); xml.setNode("track", track); xml.setNode("metadata", metadata); xml.setNode("sequential", sequential); xml.setNode("folder", isFolder || type.equals(FOLDER_TYPE)); xml.setNode("launch", launch); xml.setNode("offlinePath", offlinePath); xml.setNode("offlineName", offlineName); xml.setNode("type", type); String rgb = Integer.toHexString(color.getRGB()); xml.setNode("colour", rgb.substring(2).toUpperCase()); return xml; }
public List<String> getGlucoseDatetimesByWeek() { JodaTimeAndroid.init(mContext); DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime()); DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime()); DateTime currentDateTime = minDateTime; DateTime newDateTime = minDateTime; ArrayList<String> finalWeeks = new ArrayList<String>(); // The number of weeks is at least 1 since we do have average for the current week even if incomplete int weeksNumber = Weeks.weeksBetween(minDateTime, maxDateTime).getWeeks() + 1; DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); for (int i = 0; i < weeksNumber; i++) { newDateTime = currentDateTime.plusWeeks(1); finalWeeks.add(inputFormat.format(newDateTime.toDate())); currentDateTime = newDateTime; } return finalWeeks; }
public String getTimeAfterHeadBlockTime(int diffInMilSec) { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { Date date = sdf.parse( this.headBlockTime); Calendar c = Calendar.getInstance(); c.setTime(date); c.add( Calendar.MILLISECOND, diffInMilSec); date = c.getTime(); return sdf.format(date); } catch (ParseException e) { e.printStackTrace(); return this.headBlockTime; } }
public static void main(String[] args) { String expectedMed = "30-04-2008"; String expectedShort="30-04-08"; Locale dk = new Locale("da", "DK"); DateFormat df1 = DateFormat.getDateInstance(DateFormat.MEDIUM, dk); DateFormat df2 = DateFormat.getDateInstance(DateFormat.SHORT, dk); String medString = new String (df1.format(new Date(108, Calendar.APRIL, 30))); String shortString = new String (df2.format(new Date(108, Calendar.APRIL, 30))); System.out.println(df1.format(new Date())); System.out.println(df2.format(new Date())); if (expectedMed.compareTo(medString) != 0) { throw new RuntimeException("Error: " + medString + " should be " + expectedMed); } if (expectedShort.compareTo(shortString) != 0) { throw new RuntimeException("Error: " + shortString + " should be " + expectedShort); } }
@Test public void testAddMonth() { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = new GregorianCalendar(2016, 0, 31); System.out.println(format.format(cal.getTime())); cal.add(Calendar.MONTH, 1); System.out.println(format.format(cal.getTime())); Assert.assertTrue(cal.getTimeInMillis() == new GregorianCalendar(2016, 1, 29).getTimeInMillis()); cal.add(Calendar.MONTH, 1); System.out.println(format.format(cal.getTime())); Assert.assertTrue(cal.getTimeInMillis() == new GregorianCalendar(2016, 2, 29).getTimeInMillis()); }
protected DateFormat createFormatInstance ( final long timeRange ) { if ( hasFormat () ) { try { return new SimpleDateFormat ( this.format ); } catch ( final IllegalArgumentException e ) { return DateFormat.getInstance (); } } else { return Helper.makeFormat ( timeRange ); } }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.content_about_tab1, container, false); TextView about_text_build = (TextView) view.findViewById(R.id.about_text_build); TextView about_text_version = (TextView) view.findViewById(R.id.about_text_version); String buildDate = DateFormat.getDateInstance().format(BuildConfig.TIMESTAMP); //get the build date in locale time format if (about_text_build!=null && about_text_version!=null) { about_text_version.setText(String.format(Locale.getDefault(),"%s: %s", getString(R.string.app_version),BuildConfig.VERSION_NAME)); about_text_build.setText(String.format(Locale.getDefault(), "%s: %s", getResources().getString(R.string.about_build_date), buildDate)); } TextView aboutTextViewGitHubLink = (TextView) view.findViewById(R.id.aboutTextViewGitHubLink); aboutTextViewGitHubLink.setMovementMethod(LinkMovementMethod.getInstance()); TextView aboutTextViewMaterialLicense = (TextView) view.findViewById(R.id.aboutTextViewMaterialLicense); aboutTextViewMaterialLicense.setMovementMethod(LinkMovementMethod.getInstance()); return view; }
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(); }
/** * Indicate that the server is shutting down. * * @param token -- secret token used like a password to authenticate the shutdown command * @param delay -- the delay in seconds before jobs are no longer accepted */ @GET @Path("shutdown") @Produces(MediaType.TEXT_PLAIN) public Response shutdown(@QueryParam("token") String token, @QueryParam("delay") String delay) throws IOException { if (commandLineOptions.shutdownToken == null || token == null) { return Response.status(Response.Status.FORBIDDEN).type(MediaType.TEXT_PLAIN_TYPE).entity("No Shutdown Token").build(); } else if (!token.equals(commandLineOptions.shutdownToken)) { return Response.status(Response.Status.FORBIDDEN).type(MediaType.TEXT_PLAIN_TYPE).entity("Invalid Shutdown Token").build(); } else { long shutdownTime = System.currentTimeMillis(); if (delay != null) { try { shutdownTime += Integer.parseInt(delay) *1000; } catch (NumberFormatException e) { // XXX Ignore } } shuttingTime = shutdownTime; DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL); return Response.ok("ok: Will shutdown at " + dateTimeFormat.format(new Date(shuttingTime)), MediaType.TEXT_PLAIN_TYPE).build(); } }
@OnClick(R.id.time_left_due_date_content) void timeLeftDueDateOnClickBehavior() { DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { dueCalendar.set(Calendar.YEAR, year); dueCalendar.set(Calendar.MONTH, monthOfYear); dueCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); DateFormat sdf = android.text.format.DateFormat.getDateFormat(getBaseContext()); dueDateContent.setText(sdf.format(dueCalendar.getTime())); setDate2 = true; } }; new DatePickerDialog(this, date, dueCalendar.get(Calendar.YEAR), dueCalendar.get(Calendar.MONTH), dueCalendar.get(Calendar.DAY_OF_MONTH)).show(); }
/** * Parse date with given formatters. */ private static final Long internalParseDate (String value, DateFormat[] formats) { Date date = null; for (int i = 0; (date == null) && (i < formats.length); i++) { try { date = formats[i].parse(value); } catch (ParseException e) { // Ignore } } if (date == null) { return null; } return Long.valueOf(date.getTime()); }
/** * Parses a string using {@link SimpleDateFormat} and a given pattern. This * method parses a string at the specified parse position and if successful, * updates the parse position to the index after the last character used. * The parsing is strict and requires months to be less than 12, days to be * less than 31, etc. * * @param s string to be parsed * @param dateFormat Date format * @param tz time zone in which to interpret string. Defaults to the Java * default time zone * @param pp position to start parsing from * @return a Calendar initialized with the parsed value, or null if parsing * failed. If returned, the Calendar is configured to the GMT time zone. */ private static Calendar parseDateFormat(String s, DateFormat dateFormat, TimeZone tz, ParsePosition pp) { if (tz == null) { tz = DEFAULT_ZONE; } Calendar ret = Calendar.getInstance(tz, Locale.ROOT); dateFormat.setCalendar(ret); dateFormat.setLenient(false); final Date d = dateFormat.parse(s, pp); if (null == d) { return null; } ret.setTime(d); ret.setTimeZone(UTC_ZONE); return ret; }
public String toHtml(){ HashMap<MemoryLogger.Type, String> typeColours = new HashMap<>(); typeColours.put(MemoryLogger.Type.info, "#008000"); // LimeGreen typeColours.put(MemoryLogger.Type.debug, "blue"); typeColours.put(MemoryLogger.Type.warn, "orange"); typeColours.put(MemoryLogger.Type.error, "red"); String colour = ""; if (typeColours.containsKey(type)) colour = typeColours.get(type); message = message.replace("\n", "<br/>"); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); String text = dateFormat.format(dateTime) + " > " + tag + " - " + message; return "<font color='" + colour + "'>" + text + "</font>"; }
public Logger(Main plugin) { this.plugin = plugin; Date date = new Date(); DateFormat df = new SimpleDateFormat("Y-MM-d"); String fileName = df.format(date) + ".log"; (new File(plugin.getDataFolder() + File.separator + "logs" + File.separator)).mkdir(); file = new File(plugin.getDataFolder() + File.separator + "logs" + File.separator, fileName); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } }
private void logEntries(Collection<HistoryEntry> entries) { LocalHistory.LOG.log(Level.FINE, "LocalHistory returns {0} entries", entries.size()); // NOI18N if(LocalHistory.LOG.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); Iterator<HistoryEntry> it = entries.iterator(); while(it.hasNext()) { HistoryEntry entry = it.next(); sb.append("["); // NOI18N sb.append(DateFormat.getDateTimeInstance().format(entry.getDateTime())); sb.append(",["); // NOI18N sb.append(toString(entry.getFiles())); sb.append("]]"); // NOI18N if(it.hasNext()) sb.append(","); // NOI18N } LocalHistory.LOG.finest(sb.toString()); } }
@Test public void testDate() throws ParseException, PebbleException, IOException { PebbleEngine pebble = new PebbleEngine.Builder().loader(new StringLoader()).strictVariables(false) .defaultLocale(Locale.ENGLISH).build(); String source = "{{ realDate | date('MM/dd/yyyy') }}{{ realDate | date(format) }}{{ stringDate | date('yyyy/MMMM/d','yyyy-MMMM-d') }}"; PebbleTemplate template = pebble.getTemplate(source); Map<String, Object> context = new HashMap<>(); DateFormat format = new SimpleDateFormat("yyyy-MMMM-d", Locale.ENGLISH); Date realDate = format.parse("2012-July-01"); context.put("realDate", realDate); context.put("stringDate", format.format(realDate)); context.put("format", "yyyy-MMMM-d"); Writer writer = new StringWriter(); template.evaluate(writer, context); assertEquals("07/01/20122012-July-12012/July/1", writer.toString()); }
/** * Initialise la date */ public void setDate(String cs) { DateFormat df = DateFormat.getInstance() ; Date date ; try { date = df.parse(cs); calendar.setTime(date); } catch (ParseException e) { e.printStackTrace(); } }
public String getFormattedMonth (Date day) throws ParseException{ DateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); DateFormat outputFormat = new SimpleDateFormat("MMM", Locale.ENGLISH); String inputDate = day.getDay().toString(); java.util.Date date = input.parse(inputDate); String formattedDate = outputFormat.format(date); return formattedDate; }
private void dateRbtn() { DateFormat formateDATEddMMMM = new SimpleDateFormat("dd MMMM, yyyy"); DATEddMMMM.setText(formateDATEddMMMM.format(now.getTime())); DATEddMMMM.setToggleGroup(daterbtnGroup); DATEddMMMM.setUserData("dd MMMM, yyyy"); DateFormat formateDATEddMMM = new SimpleDateFormat("dd MMM, yyyy"); DATEddMMM.setText(formateDATEddMMM.format(now.getTime())); DATEddMMM.setToggleGroup(daterbtnGroup); DATEddMMM.setUserData("dd MMM, yyyy"); DateFormat formateDATEddMM = new SimpleDateFormat("dd-MM-yyyy"); DATEddMM.setText(formateDATEddMM.format(now.getTime())); DATEddMM.setToggleGroup(daterbtnGroup); DATEddMM.setUserData("dd-MM-yyyy"); DateFormat formateDATEEEddMMM = new SimpleDateFormat("EE dd MMMM, yyyy"); DATEEEddMMM.setText(formateDATEEEddMMM.format(now.getTime())); DATEEEddMMM.setToggleGroup(daterbtnGroup); DATEEEddMMM.setUserData("EE dd MMMM, yyyy"); DateFormat formateDATEMMM = new SimpleDateFormat("MMMM dd, yyyy"); DATEMMM.setText(formateDATEMMM.format(now.getTime())); DATEMMM.setToggleGroup(daterbtnGroup); DATEMMM.setUserData("MMMM dd, yyyy"); switch (new DateFormatManager().getDateFormat()) { case "dd MMMM, yyyy": DATEddMMMM.setSelected(true); break; case "dd MMM, yyyy": DATEddMMM.setSelected(true); break; case "dd-MM-yyyy": DATEddMM.setSelected(true); break; case "EE dd MMMM, yyyy": DATEEEddMMM.setSelected(true); break; default: DATEMMM.setSelected(true); break; } }
public static String getCurrentWeekday() { weeks = 0; int mondayPlus = getMondayPlus(); GregorianCalendar currentDate = new GregorianCalendar(); currentDate.add(GregorianCalendar.DATE, mondayPlus + 6); Date monday = currentDate.getTime(); DateFormat df = DateFormat.getDateInstance(); String preMonday = df.format(monday); return preMonday; }
private long parseDateString(String dateStr) { try { DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd"); return formatter.parse(dateStr).getTime(); } catch (ParseException e) { throw new RuntimeException("Cannot parse: " + dateStr); } }
/** * (月)得当时间段内的所有月份 * * @param StartDate * @param endDate * @return */ public static List<String> getYearMouthBy(String StartDate, String endDate) { DateFormat df = new SimpleDateFormat("yyyy-MM"); Date date1 = null; // 开始日期 Date date2 = null; // 结束日期 try { date1 = df.parse(StartDate); date2 = df.parse(endDate); } catch (ParseException e) { e.printStackTrace(); } Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); // 定义集合存放月份 List<String> list = new ArrayList<String>(); // 添加第一个月,即开始时间 list.add(df.format(date1)); c1.setTime(date1); c2.setTime(date2); while (c1.compareTo(c2) < 0) { c1.add(Calendar.MONTH, 1);// 开始日期加一个月直到等于结束日期为止 Date ss = c1.getTime(); String str = df.format(ss); list.add(str); } return list; }
public Date tryConvert(String text, String pattern) { DateFormat dateFormat = new SimpleDateFormat(pattern); dateFormat.setLenient(false); try { return dateFormat.parse(text); } catch (ParseException ex) { logger.debug(ex.getMessage(), ex); } return null; }
public static String formatShortTime(Context context, Date time) { // Android DateFormatter will honor the user's current settings. DateFormat format = android.text.format.DateFormat.getTimeFormat(context); // Override with Timezone based on settings since users can override their phone's timezone // with Pacific time zones. TimeZone tz = SettingsUtils.getDisplayTimeZone(context); if (tz != null) { format.setTimeZone(tz); } return format.format(time); }
private static String toLocale_helper(double t, int methodId) { DateFormat formatter; switch (methodId) { case Id_toLocaleString: if (localeDateTimeFormatter == null) { localeDateTimeFormatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); } formatter = localeDateTimeFormatter; break; case Id_toLocaleTimeString: if (localeTimeFormatter == null) { localeTimeFormatter = DateFormat.getTimeInstance(DateFormat.LONG); } formatter = localeTimeFormatter; break; case Id_toLocaleDateString: if (localeDateFormatter == null) { localeDateFormatter = DateFormat.getDateInstance(DateFormat.LONG); } formatter = localeDateFormatter; break; default: throw new AssertionError(); // unreachable } synchronized (formatter) { return formatter.format(new Date((long) t)); } }
/** * Serialize all the class attributes * @return * @throws Exception */ @Override public JsonNode jsonSerialization() throws Exception { JsonNode jsonError; ObjectMapper mapper = new ObjectMapper(); DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); mapper.setDateFormat(myDateFormat); jsonError = mapper.convertValue(this, JsonNode.class); return jsonError; }
/** * Creates a tool tip generator using the supplied date formatter. * * @param dateFormatter the date formatter (<code>null</code> not permitted). * @param numberFormatter the number formatter (<code>null</code> not permitted). */ public HighLowItemLabelGenerator(DateFormat dateFormatter, NumberFormat numberFormatter) { if (dateFormatter == null) { throw new IllegalArgumentException("Null 'dateFormatter' argument."); } if (numberFormatter == null) { throw new IllegalArgumentException("Null 'numberFormatter' argument."); } this.dateFormatter = dateFormatter; this.numberFormatter = numberFormatter; }
public static String getDisplayCreationTimeForSession(Session in_session) { try { if (in_session.getCreationTime() == 0) { return ""; } DateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT); return formatter.format(new Date(in_session.getCreationTime())); } catch (IllegalStateException ise) { // ignore: invalidated session return ""; } }
private void checkParanoia(Profile profile) { if (!profile.response.avatar.equals("")) { getMvpView().showAvatar(profile.response.avatar); } else { getMvpView().showDefaultAvatar(); } getMvpView().showUsername(profile.response.username); getMvpView().showJoinedDate(profile.response.stats.joinedDate); getMvpView().showUserClass(profile.response.personal.mclass); if (!profile.response.profileText.equals("")) { getMvpView().showUserDescription(profile.response.profileText); } else { getMvpView().showUserDescriptionEmpty(); } //workaround due to paranoid users having "" as lastAccess, rather than null. When this is fixed, change the type on Profile back to Date and let gson auto parse it DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); if(profile.response.stats.lastAccess.equals("")) getMvpView().showLastSeenParanoid(); else try { getMvpView().showLastSeen(format.parse(profile.response.stats.lastAccess)); } catch (ParseException e) { e.printStackTrace(); } if(profile.response.stats.ratio == null || profile.response.stats.requiredRatio == null) getMvpView().showRatioParanoid(); else getMvpView().showRatio(profile.response.stats.ratio, profile.response.stats.requiredRatio); if(profile.response.ranks.uploaded == null) getMvpView().showUploadedParanoid(); else getMvpView().showUploaded(profile.response.ranks.uploaded); if(profile.response.ranks.uploads == null) getMvpView().showNumUploadsParanoid(); else getMvpView().showNumUploads(profile.response.ranks.uploads); if(profile.response.ranks.downloaded == null) getMvpView().showDownloadedParanoid(); else getMvpView().showDownloaded(profile.response.ranks.downloaded); if(profile.response.ranks.requests == null) getMvpView().showRequestsParanoid(); else getMvpView().showRequestsFilled(profile.response.ranks.requests); if(profile.response.ranks.bounty == null) getMvpView().showBountySpentParanoid(); else getMvpView().showBountySpent(profile.response.ranks.bounty); if(profile.response.ranks.posts == null) getMvpView().showNumForumPostsParanoid(); else getMvpView().showNumForumPosts(profile.response.ranks.posts); if(profile.response.ranks.artists == null) getMvpView().showArtistsAddedParanoid(); else getMvpView().showArtistsAdded(profile.response.ranks.artists); if(profile.response.ranks.overall == null) getMvpView().showOverallRankParanoid(); else getMvpView().showOverallRank(profile.response.ranks.overall); }
public Date parse(final String date) throws ParseException { final DateFormat format = fetchFromPool(); try { return format.parse(date); } finally { pool.putInPool(format); } }
@Test public void can_use_template_create_fhir_appointment_with_calculated_datetime_variable() throws Exception { interpreter = buildInterpreterWithFhirPluginAndCurrentDateTime("2013-04-20T14:00:00"); guideline = loadGuideline("use_template_fhir_appointment_set_with_calculated_datetime.v0.1.gdl2"); List<Guideline> guidelines = Collections.singletonList(guideline); output = interpreter.executeGuidelines(guidelines, input); assertThat(output.get(0).getRoot(), instanceOf(Appointment.class)); Appointment appointment = (Appointment) output.get(0).getRoot(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertThat(dateFormat.format(appointment.getRequestedPeriod().get(0).getStart()), is("2013-04-20T14:00:00")); assertThat(dateFormat.format(appointment.getRequestedPeriod().get(0).getEnd()), is("2013-07-20T14:00:00")); }
public void setData(String data) throws ParseException { if (!"".equals(data)) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); this.data = df.parse(data); } else { this.data = null; } }
/** * 将日志记录到文件中 * @param content 记录内容 */ public static void RecordLog(char level, String content){ if (level == 'X'){ return; } if (!AppConstants.DEBUG && !GlobalSettingMng.getSetting().getIsRecordLog()){ return; } File tmpFile = getLogFile(); if (tmpFile == null){ return; } try { RandomAccessFile raf = new RandomAccessFile(tmpFile, "rwd"); raf.seek(tmpFile.length()); DateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss", Locale.getDefault()); String tmpStr = String.format("%s %c %s\r\n", dateFormat.format(new java.util.Date()), level, content); raf.write(tmpStr.getBytes()); raf.close(); } catch (Exception ex){ AppConstants.XLog("Record log ex: " + ex.toString()); } }
/** * Converts the given log message to the HTML format. * * @param message * The message to convert to the HTML format * @return The given message in the HTML format */ private static String messageToHtml(final LogMessage message) { final String content = message.getMessage(); final ELogLevel level = message.getLogLevel(); final long timestamp = message.getTimestamp(); final Date date = new Date(timestamp); final String timestampFormat = DateFormat.getDateTimeInstance().format(date); final String cssLogClass; if (level == ELogLevel.INFO) { cssLogClass = CLASS_LOG_INFO; } else if (level == ELogLevel.DEBUG) { cssLogClass = CLASS_LOG_DEBUG; } else if (level == ELogLevel.ERROR) { cssLogClass = CLASS_LOG_ERROR; } else { throw new AssertionError(); } final StringBuilder sb = new StringBuilder(); sb.append("<span class=\"").append(cssLogClass).append("\">"); sb.append("<span class=\"").append(CLASS_LOG_TIMESTAMP).append("\">"); sb.append(timestampFormat); sb.append(":</span>"); sb.append("<span class=\"").append(CLASS_LOG_CONTENT).append("\">"); sb.append(escapeHtml(content)); sb.append("</span>"); sb.append("</span>"); sb.append(MESSAGE_SEPARATOR); return sb.toString(); }
public String put(String key, Object value) { String strValue; if (value == null) { strValue = null; } else if (value instanceof String) { strValue = (String) value; } else if (value instanceof Integer) { strValue = ((Integer) value).toString(); } else if (value instanceof Long) { strValue = ((Long) value).toString(); } else if (value instanceof Float) { strValue = ((Float) value).toString(); } else if (value instanceof Double) { strValue = ((Double) value).toString(); } else if (value instanceof Boolean) { strValue = ((Boolean) value).toString(); } else if (value instanceof Date) { DateFormat format = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT); format.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE)); strValue = format.format((Date) value); } else { strValue = value.toString(); } return this.put(key, strValue); }
/** * @return current time with respect to the format yyyy-MM-dd-HH-MM-ss */ public static String now() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); Date date = new Date(); return dateFormat.format(date); }
/** * Tries to parse the text field for a valid date. */ private void tryParse() { if (textField.getText() != null && textField.getText().length() > 0) { try { // Double parse the date here, since e.g. 01.01.1 is parsed as year 1, and then formatted as 01.01.01 and then parsed as year 2001. // This might lead to an undesired date. DateFormat dateFormat = getActualDateFormat(); Date parsedDate = dateFormat.parse(textField.getText()); // If the parsed exceeds the min or max date, take the min or max date instead. Date actualDate = parsedDate; if (normalizedMinDate.get() != null && parsedDate.before(normalizedMinDate.get())) { actualDate = null; datePicker.errorProperty().set(DatePicker.Error.DATE_LESS_THAN_MIN); } if (normalizedMaxDate.get() != null && parsedDate.after(normalizedMaxDate.get())) { actualDate = null; datePicker.errorProperty().set(DatePicker.Error.DATE_GREATER_THAN_MAX); } if (datePicker.errorProperty().get() != null) { getSkinnable().valueProperty().set(actualDate); updateTextField(); } else if (getSkinnable().valueProperty().get() == null || getSkinnable().valueProperty().get() != null && actualDate != null && actualDate.getTime() != getSkinnable().valueProperty().get().getTime()) { getSkinnable().valueProperty().set(actualDate); calendarView.selectedDateProperty().set(actualDate); getSkinnable().errorProperty().set(null); updateTextField(); } } catch (ParseException e) { getSkinnable().errorProperty().set(DatePicker.Error.UNPARSABLE); getSkinnable().valueProperty().set(null); updateTextField(); } } else { getSkinnable().errorProperty().set(null); getSkinnable().valueProperty().set(null); updateTextField(); } }
/** * Initialized the {@link StatePool}. This API also reloads the previously * persisted state. Note that the {@link StatePool} should be initialized only * once. */ public void initialize(Configuration conf) throws Exception { if (isInitialized) { throw new RuntimeException("StatePool is already initialized!"); } this.conf = conf; String persistDir = conf.get(DIR_CONFIG); reload = conf.getBoolean(RELOAD_CONFIG, false); persist = conf.getBoolean(PERSIST_CONFIG, false); // reload if configured if (reload || persist) { System.out.println("State Manager initializing. State directory : " + persistDir); System.out.println("Reload:" + reload + " Persist:" + persist); if (persistDir == null) { throw new RuntimeException("No state persist directory configured!" + " Disable persistence."); } else { this.persistDirPath = new Path(persistDir); } } else { System.out.println("State Manager disabled."); } // reload reload(); // now set the timestamp DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy-hh'H'-mm'M'-ss'S'"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); timeStamp = formatter.format(calendar.getTime()); isInitialized = true; }