I'm displaying four data fields in a single column of a gridview using template field. One of the data fields is a date field. Instead of showing normal date, I want to display relative hours/days. (like: 2 hours ago/ 2 days ago). How can i manipulate the date field 开发者_JAVA百科inside the template field column. Please suggest.
Thanks.
You can use <%# Eval("Date Field") %> to manipulate the data that is bound to the column at runtime. You can even call functions in your code-behind by doing something like this:
<%# this.MyFunction(Eval("Date Field Name")) %>
There may be a better way to do it, but this has worked for me in the past. Note that Eval returns an object
.
If other views/pages will use that format, you might want to think about putting that in a business service layer or some utility function so it's not buried/duplicated in the UI.
// Business Service
public IList<Person> GetAllActivePeople()
{
var people = _yourDataRepository.FindActive();
foreach(var p in people)
{
p.MyRelativeDateField = ConvertToRelativeHoursDays(p.MyDateField);
}
return people;
}
// probably better as a utility class if other dates of other objects can use this...
private string ConvertToRelativeHoursDays(DateTime someDate)
{
// implement formatting here
}
精彩评论