org.ocpsoft.prettytime.PrettyTime Java Examples

The following examples show how to use org.ocpsoft.prettytime.PrettyTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultViewObjects.java    From mamute with Apache License 2.0 6 votes vote down vote up
public void include() {
	menuInfo.include();
	sideBarInfo.include();

	result.include("env", env);
	result.include("prettyTimeFormatter", new PrettyTime(locale));
	result.include("literalFormatter", brutalDateFormat.getInstance("date.joda.pattern"));
	result.include("currentUrl", getCurrentUrl());
	result.include("contextPath", req.getContextPath());
	result.include("deployTimestamp", deployTimestamp());
	result.include("shouldShowAds", ads.shouldShowAds());
	result.on(NotFoundException.class).notFound();
	result.on(BannedUserException.class)
			.include("errors", asList(messageFactory.build("error", "user.errors.banned")))
			.redirectTo(AuthController.class).loginForm("");

}
 
Example #2
Source File: TimeUtils.java    From OmniList with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String getPrettyTime(Date date, Locale locale) {
    if (date == null) {
        return "";
    }
    PrettyTime pt = new PrettyTime();
    if (locale != null) {
        pt.setLocale(locale);
    }
    return pt.format(date);
}
 
Example #3
Source File: RelativeTime.java    From kaif with Apache License 2.0 6 votes vote down vote up
@Override
public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() < 1) {
    throw new TemplateModelException("require an Instant as argument");
  }
  if (arguments.size() > 2) {
    throw new TemplateModelException("too many arguments");
  }
  PrettyTime prettyTime = new PrettyTime(Environment.getCurrentEnvironment().getLocale());
  // only support day unit now
  if (arguments.size() == 2 && arguments.get(1).toString().equals("Day")) {
    List<TimeUnit> units = prettyTime.getUnits()
        .stream()
        .filter(timeUnit -> timeUnit.getMillisPerUnit() > new Day().getMillisPerUnit())
        .collect(Collectors.toList());
    units.forEach(prettyTime::removeUnit);
  }

  StringModel stringModel = (StringModel) arguments.get(0);
  Instant instant = (Instant) stringModel.getAdaptedObject(Instant.class);
  return prettyTime.format(Date.from(instant));
}
 
Example #4
Source File: ObservationMarkerCollection.java    From mage-android with Apache License 2.0 6 votes vote down vote up
@Override
     public View getInfoWindow(Marker marker) {
         final Observation observation = mapObservations.getMarkerObservation(marker.getId());
         if (observation == null) {
             return null;
         }

         LayoutInflater inflater = LayoutInflater.from(context);
         View v = inflater.inflate(R.layout.observation_infowindow, null);

ObservationProperty primaryField = observation.getPrimaryField();

String type = primaryField != null ? primaryField.getValue().toString() : "Observation";

         TextView primary = v.findViewById(R.id.observation_primary);
         primary.setText(type);

         TextView date = v.findViewById(R.id.observation_date);
         date.setText(new PrettyTime().format(observation.getTimestamp()));

         return v;
     }
 
Example #5
Source File: Projects.java    From intra42 with Apache License 2.0 6 votes vote down vote up
@Override
public String getDetail(Context context) {
    ProjectsSessions sessions = ProjectsSessions.getSessionSubscribable(sessionsList);
    String time = null;

    if (sessions != null) {
        PrettyTime p = new PrettyTime(Locale.getDefault());
        time = p.formatDuration(new Date(System.currentTimeMillis() - sessions.estimateTime * 1000));
    }

    String ret = "";
    if (time != null)
        ret += time + " ";
    ret += "T" + String.valueOf(tier);

    return ret;
}
 
Example #6
Source File: TravisApiTest.java    From jandy with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGetBuild() throws Exception {
  long buildId = 79083233;
  server.expect(requestTo("https://api.travis-ci.org/builds/"+buildId))
          .andExpect(method(HttpMethod.GET))
          .andExpect(header(HttpHeaders.ACCEPT, "application/vnd.travis-ci.2+json"))
          .andRespond(withSuccess(output, MediaType.APPLICATION_JSON_UTF8));

  TResult result = client.getBuild(79083233);

  System.out.println(result);

  Calendar calendar = DatatypeConverter.parseDateTime((String)result.getBuild().getStartedAt());
  PrettyTime p = new PrettyTime(Locale.ENGLISH);

  System.out.println(p.format(calendar));
  
  assertThat(result.getBuild().getCommitId(), is(result.getCommit().getId()));
  assertThat(result.getCommit().getId(), is(22542817L));
  assertThat(result.getCommit().getMessage(), is("add depedency of icu4j"));
  assertThat(result.getCommit().getCommitterName(), is("JCooky"));
}
 
Example #7
Source File: Reporter.java    From jandy with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendMail(User user, Build current) throws MessagingException {
  mailSender.send(msg -> {
    GHUser ghUser = null;
    if (current.getCommit() != null)
      ghUser = github.getUser(current.getCommit().getCommitterName());

    PrettyTime p = new PrettyTime(Locale.ENGLISH);
    if (current.getFinishedAt() != null)
      current.setBuildAt(p.format(DatatypeConverter.parseDateTime(current.getFinishedAt())));

    HashMap<String, Object> model = new HashMap<>();
    model.put("project", current.getBranch().getProject());
    model.put("build", current);
    model.put("committerAvatarUrl", ghUser == null ? null : user.getAvatarUrl());

    MimeMessageHelper h = new MimeMessageHelper(msg, false, "UTF-8");
    h.setFrom("[email protected]");
    h.setTo(user.getEmail());
    h.setSubject("Jandy Performance Report");
    h.setText(FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfigurer.getConfiguration().getTemplate("email.ftl"), model), true);


  });
}
 
Example #8
Source File: TopicListAdapter.java    From Elephant with Apache License 2.0 5 votes vote down vote up
@SuppressLint("SimpleDateFormat")
public TopicListAdapter(Context context, List<TopicEntity> datas) {
    this.mContext = context;
    this.mDatas = datas;
    mLocale = mContext.getResources().getConfiguration().locale;
    mPrettyTime = new PrettyTime(mLocale);
    mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
 
Example #9
Source File: DateTimeUtils.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getPrettyDateValue(LocalDateTime dateTime, ZoneId zoneId, Locale locale) {

        if (dateTime == null) {
            return "";
        }
        PrettyTime p = new PrettyTime(locale);
        return p.format(convertLocalDateTimeToDate(dateTime, zoneId));
    }
 
Example #10
Source File: UserUIContext.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String formatPrettyTime(LocalDate localDate) {
    if (localDate != null) {
        Date date = Date.from(localDate.atStartOfDay(getUserTimeZone()).toInstant());
        PrettyTime p = new PrettyTime();
        return p.format(date);
    } else {
        return "";
    }
}
 
Example #11
Source File: LocationMarkerCollection.java    From mage-android with Apache License 2.0 5 votes vote down vote up
@Override
public View getInfoWindow(final Marker marker) {
	Pair<Location, User> pair = markerIdToPair.get(marker.getId());
	final Location location = pair.first;
	final User user = pair.second;
	if (user == null || location == null) {
		return null;
	}

	LayoutInflater inflater = LayoutInflater.from(context);
	final View v = inflater.inflate(R.layout.people_info_window, null);

	TextView name = v.findViewById(R.id.name);
	name.setText(user.getDisplayName());

	TextView date = v.findViewById(R.id.date);
	date.setText(new PrettyTime().format(location.getTimestamp()));

	final ImageView avatarView = v.findViewById(R.id.avatarImageView);
	Bitmap avatar = avatars.get(user.getId());
	if (avatar == null) {
		GlideApp.with(context)
				.asBitmap()
				.load(Avatar.Companion.forUser(user))
				.placeholder(R.drawable.ic_person_gray_24dp)
				.circleCrop()
				.into(getTarget(avatarView, marker, user));
	} else {
		avatarView.setImageBitmap(avatar);
	}

	return v;
}
 
Example #12
Source File: PippoHelper.java    From pippo with Apache License 2.0 5 votes vote down vote up
public PippoHelper(Messages messages, String language, Locale locale, Router router) {
    this.messages = messages;
    this.language = language;
    this.locale = locale;
    this.router = router;
    this.prettyTime = new PrettyTime(locale);
    this.webjarsPatternRef = new AtomicReference<>();
    this.publicPatternRef = new AtomicReference<>();
}
 
Example #13
Source File: PippoGroovyTemplate.java    From pippo with Apache License 2.0 5 votes vote down vote up
public String prettyTime(Object input) {
    if (prettyTime == null) {
        this.prettyTime = new PrettyTime(locale);
    }
    Date date = getDateObject(input);

    return prettyTime.format(date);
}
 
Example #14
Source File: PippoHelper.java    From pippo with Apache License 2.0 5 votes vote down vote up
public PippoHelper(Messages messages, String language, Locale locale, Router router) {
    this.messages = messages;
    this.language = language;
    this.locale = locale;
    this.router = router;
    this.prettyTime = new PrettyTime(locale);
    this.webjarsPatternRef = new AtomicReference<>();
    this.publicPatternRef = new AtomicReference<>();
}
 
Example #15
Source File: ConversationDetailActivity.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    setContentView(R.layout.awesome_activity_detail);

    mApp = (ImApp)getApplication();

    mConvoView = new ConversationView(this);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
  //  appBarLayout = (AppBarLayout)findViewById(R.id.appbar);
    mRootLayout = findViewById(R.id.main_content);

    mPrettyTime = new PrettyTime(getCurrentLocale());

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    applyStyleForToolbar();

    collapseToolbar();

    getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
    );

}
 
Example #16
Source File: UserMessageAdapter.java    From Elephant with Apache License 2.0 5 votes vote down vote up
@SuppressLint("SimpleDateFormat")
public UserMessageAdapter(Context context, List<MessageEntity> messageList) {
    this.mContext = context;
    this.mMessageList = messageList;
    mLocale = mContext.getResources().getConfiguration().locale;
    mPrettyTime = new PrettyTime(mLocale);
    mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
 
Example #17
Source File: ConversationDetailActivity.java    From zom-android-matrix with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    setContentView(getLayoutFileId());
    mApp = (ImApp)getApplication();
    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    mConvoView = createConvoView();

  //  appBarLayout = (AppBarLayout)findViewById(R.id.appbar);
    mRootLayout = findViewById(R.id.main_content);

    mPrettyTime = new PrettyTime(getCurrentLocale());

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    applyStyleForToolbar();

    collapseToolbar();

    getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
    );

}
 
Example #18
Source File: DateTool.java    From intra42 with Apache License 2.0 5 votes vote down vote up
static public String getDuration(Date date) {
    if (date == null)
        return null;

    PrettyTime prettyTime = new PrettyTime(Locale.getDefault());
    List<Duration> duration = prettyTime.calculatePreciseDuration(date);
    prettyTime.formatDurationUnrounded(duration);

    return prettyTime.formatDurationUnrounded(duration);
}
 
Example #19
Source File: DateTool.java    From intra42 with Apache License 2.0 5 votes vote down vote up
static public String getDuration(Date before, Date after) {
    if (before == null || after == null)
        return null;

    Date date = new Date();
    date.setTime(date.getTime() - (after.getTime() - before.getTime()));
    PrettyTime prettyTime = new PrettyTime(Locale.getDefault());
    List<Duration> duration = prettyTime.calculatePreciseDuration(date);
    prettyTime.formatDurationUnrounded(duration);

    return prettyTime.formatDurationUnrounded(duration);
}
 
Example #20
Source File: TimeFormatter.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
private PrettyTime getPrettyTime() {
    if (this.prettyTime == null) {
        this.prettyTime = new PrettyTime(this.locale);
    }

    return this.prettyTime;
}
 
Example #21
Source File: StatsCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private MessageEmbed.Field getPlatformStats(Map<String, Metric> metricMap) {
    String value = getGaugeValue(metricMap, "jvm.uptime", e -> {
        Date date = new Date();
        date.setTime(date.getTime() - (long) e);
        return new PrettyTime(contextService.getLocale()).format(date);
    });
    return value != null ? new MessageEmbed.Field(messageService.getMessage("discord.command.stats.platform"), value, false) : null;
}
 
Example #22
Source File: Utils.java    From Hify with MIT License 5 votes vote down vote up
public static String DateToTimeFormat(String oldstringDate){
    PrettyTime p = new PrettyTime(Locale.ENGLISH);
    String isTime = null;
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
                Locale.ENGLISH);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = sdf.parse(oldstringDate);
        isTime = p.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return isTime;
}
 
Example #23
Source File: XMPPManager.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
public String getLastSeenMessage(String jid) {
    if (!isConnected() || !connection.isAuthenticated()) {
        return LocaleController.getString("Offline", R.string.Offline);
    }
    try {
        LastActivityManager lastActivityManager = LastActivityManager.getInstanceFor(connection);
        LastActivity activity = lastActivityManager.getLastActivity(JidCreate.bareFrom(jid));

        int lastSeenBySeconds = Utilities.parseInt(activity.lastActivity + "");

        String lastSeenMessage = "";
        lastSeenMessage = LocaleController.getString("Offline", R.string.Offline);
        if (lastSeenBySeconds >= 1) {
            PrettyTime p = new PrettyTime();
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, -1 * lastSeenBySeconds);

            lastSeenMessage = LocaleController.formatDateOnline(cal.getTime()); //p.format(cal.getTime());
        } else {
            lastSeenMessage = LocaleController.getString("Offline", R.string.Offline);
        }
        //FileLog.e("LAST ACTIVITY","" + ""+ "" + lastSeenBySeconds +"  "+jid);
        return lastSeenMessage;

    } catch (Exception e) {
        e.printStackTrace();
        return LocaleController.getString("Offline", R.string.Offline);
    }
    //return "Offline";
}
 
Example #24
Source File: PrettyTimeHelperTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPrettyTimeFactory() throws InterruptedException {

    PrettyTimeHelper helper = new PrettyTimeHelper(locale -> {
        PrettyTime prettyTime = new PrettyTime(locale);
        TimeFormat timeFormat = prettyTime.removeUnit(JustNow.class);
        JustNow justNow = new JustNow();
        justNow.setMaxQuantity(1000L * 2L);
        prettyTime.registerUnit(justNow, timeFormat);
        return prettyTime;
    });

    // Just to init the resolver
    MustacheEngine engine = MustacheEngineBuilder.newBuilder()
            .omitServiceLoaderConfigurationExtensions()
            .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH))
            .addResolver(new ThisResolver())
            .registerHelper("pretty", helper).build();

    Resources_en bundle = new Resources_en();
    assertEquals(bundle.getString("JustNowPastPrefix"),
            engine.compileMustache("pretty_helper_custom_factory_01",
                    "{{pretty this}}")
                    .render(new Date().getTime() - 1000L));
    assertEquals("4 " + bundle.getString("SecondPluralName")
            + bundle.getString("SecondPastSuffix"), engine
                    .compileMustache("pretty_helper_custom_factory_02",
                            "{{pretty this}}")
                    .render(new Date().getTime() - 4000L));
}
 
Example #25
Source File: PrettyTimeResolverTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPrettyTimeFactory() throws InterruptedException {

    PrettyTimeResolver resolver = new PrettyTimeResolver(100,
            locale -> {
                PrettyTime prettyTime = new PrettyTime(locale);
                TimeFormat timeFormat = prettyTime.removeUnit(JustNow.class);
                JustNow justNow = new JustNow();
                justNow.setMaxQuantity(1000L * 2L);
                prettyTime.registerUnit(justNow, timeFormat);
                return prettyTime;
            });

    // Just to init the resolver
    MustacheEngineBuilder.newBuilder()
            .omitServiceLoaderConfigurationExtensions()
            .setProperty(PrettyTimeResolver.ENABLED_KEY, true)
            .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH))
            .addResolver(resolver).build();

    Resources_en bundle = new Resources_en();
    assertEquals(bundle.getString("JustNowPastPrefix"), resolver
            .resolve(new Date().getTime() - 1000L, "prettyTime", null));
    assertEquals(
            "4 " + bundle.getString("SecondPluralName")
                    + bundle.getString("SecondPastSuffix"),
            resolver.resolve(new Date().getTime() - 4000L, "prettyTime",
                    null));
}
 
Example #26
Source File: DateTimeUtils.java    From Bus-Tracking-Parent with GNU General Public License v3.0 5 votes vote down vote up
public static String getPreetyTimeString(String this_date) {
    dateFormat = new SimpleDateFormat(DATE_FORMAT_STR);
    date = new Date();
    try {
        date = dateFormat.parse(this_date);
        PrettyTime prettyTime = new PrettyTime();
        return prettyTime.format(date);
    } catch (NullPointerException|ParseException p) {
        L.err("Cant parse date:" + this_date);
        return "";
    }
}
 
Example #27
Source File: DefaultPrettyTimeFactory.java    From trimou with Apache License 2.0 4 votes vote down vote up
@Override
public PrettyTime createPrettyTime(Locale locale) {
    return new PrettyTime(locale);
}
 
Example #28
Source File: PrettyTimeUtils.java    From es with Apache License 2.0 4 votes vote down vote up
/**
 * 美化时间 如显示为 1小时前 2分钟前
 *
 * @return
 */
public static final String prettyTime(Date date) {
    PrettyTime p = new PrettyTime();
    return p.format(date);

}
 
Example #29
Source File: PrettyTimeExtension.java    From pippo with Apache License 2.0 4 votes vote down vote up
private PrettyTime getPrettyTime(Locale locale) {
    return prettyTimeCache.computeIfAbsent(locale, PrettyTime::new);
}
 
Example #30
Source File: PrettyTimeMethod.java    From pippo with Apache License 2.0 4 votes vote down vote up
public PrettyTimeMethod(Locale locale) {
    this.prettyTime = new PrettyTime(locale);
}