Java Code Examples for java.text.DateFormat

The following are top voted examples for showing how to use java.text.DateFormat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: neoscada   File: EventConverter.java   View source code 8 votes vote down vote up
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 );
}
 
Example 2
Project: lams   File: FastHttpDateFormat.java   View source code 6 votes vote down vote up
/**
 * 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();
    }

}
 
Example 3
Project: Equella   File: BlackboardContent.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: SOS-The-Healthcare-Companion   File: DatabaseHandler.java   View source code 6 votes vote down vote up
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;
}
 
Example 5
Project: EosCommander   File: EosChainInfo.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 6
Project: openjdk-jdk10   File: Bug5096553.java   View source code 6 votes vote down vote up
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);
      }
}
 
Example 7
Project: jetfuel   File: DateTests.java   View source code 6 votes vote down vote up
@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());

}
 
Example 8
Project: neoscada   File: XAxisDynamicRenderer.java   View source code 6 votes vote down vote up
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 );
    }
}
 
Example 9
Project: Simple-Search   File: InformationFragment.java   View source code 6 votes vote down vote up
@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;
}
 
Example 10
Project: GitHub   File: NoteActivity.java   View source code 6 votes vote down vote up
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 11
Project: appinventor-extensions   File: BuildServer.java   View source code 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example 12
Project: Sanxing   File: OperateTimeLeftActivityBase.java   View source code 6 votes vote down vote up
@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();
}
 
Example 13
Project: tomcat7   File: FastHttpDateFormat.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 14
Project: calcite-avatica   File: DateTimeUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: uob-timetable-android   File: MemoryLogger.java   View source code 6 votes vote down vote up
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>";
        }
 
Example 16
Project: AsgardAscension   File: Logger.java   View source code 6 votes vote down vote up
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();
		}
	}
}
 
Example 17
Project: incubator-netbeans   File: LocalHistoryProvider.java   View source code 6 votes vote down vote up
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());
    }
}
 
Example 18
Project: de.flapdoodle.solid   File: CoreFiltersTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 19
Project: ChronoBike   File: DateUtil.java   View source code 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example 20
Project: MBSE-Vacation-Manager   File: Calender2TextUtil.java   View source code 5 votes vote down vote up
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; 	
}
 
Example 21
Project: Money-Manager   File: SettingsController.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 22
Project: xlight_android_native   File: DateUtil.java   View source code 5 votes vote down vote up
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;
}
 
Example 23
Project: elasqlbench   File: TpceTestbedLoaderProc.java   View source code 5 votes vote down vote up
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);
	}
}
 
Example 24
Project: kettle_support_kettle8.0   File: DateUtils.java   View source code 5 votes vote down vote up
/**
 * (月)得当时间段内的所有月份
 * 
 * @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;
}
 
Example 25
Project: lemon   File: DateConverter.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: iosched-reader   File: TimeUtils.java   View source code 5 votes vote down vote up
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);
}
 
Example 27
Project: HL4A   File: NativeDate.java   View source code 5 votes vote down vote up
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));
    }
}
 
Example 28
Project: CS6310O01   File: Administrator.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Project: parabuild-ci   File: HighLowItemLabelGenerator.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 30
Project: lazycat   File: JspHelper.java   View source code 5 votes vote down vote up
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 "";
	}
}
 
Example 31
Project: REDAndroid   File: ProfilePresenter.java   View source code 5 votes vote down vote up
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);
}
 
Example 32
Project: lams   File: ThreadSafeSimpleDateFormat.java   View source code 5 votes vote down vote up
public Date parse(final String date) throws ParseException {
    final DateFormat format = fetchFromPool();
    try {
        return format.parse(date);
    } finally {
        pool.putInPool(format);
    }
}
 
Example 33
Project: gdl2   File: UseTemplateExpressionTest.java   View source code 5 votes vote down vote up
@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"));
}
 
Example 34
Project: PosJava   File: Cotacao.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 35
Project: MainCalendar   File: Helper.java   View source code 5 votes vote down vote up
/**
 * 将日志记录到文件中
 * @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());
    }
}
 
Example 36
Project: BrainBridge   File: HtmlLogger.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 37
Project: framework   File: AlipayHashMap.java   View source code 5 votes vote down vote up
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);
}
 
Example 38
Project: GazePlay   File: Utils.java   View source code 5 votes vote down vote up
/**
 * @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);

}
 
Example 39
Project: graphing-loan-analyzer   File: DatePickerSkin.java   View source code 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 40
Project: hadoop   File: StatePool.java   View source code 5 votes vote down vote up
/**
 * 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;
}