I work in MVC5 and EntityFramework for displaying data into View.
right now in my view data format is :- 10/22/2014 12:00:00 AM
But i want only date :- 22/10/2014 in this format
i try this code but it not working
#if (item.chekin_on_after != null)
{ #Html.DisplayFor(modelItem => item.chekin_on_after, "ShortDateTime")}
I also follow few link in stackoverflow but not helpful Date Format using Html.DisplayFor() in MVC5, Display only date and no time
I didn’t use #html.DisplayFor().Instead of this I use
#Convert.ToString(string.Format("{0:dd/MM/yyyy}", item.chekin_on_after))
And it works perfectly.
Try to use below attribute in your model class.
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime chekin_on_after { get; set; }
Hope it helps..
You can use this function in your controller before populating the data to model :
public static System.DateTime ParseDate(string value, string style)
{
DateTime blankDate = default(DateTime);
if ((value != null & value.Length > 0)) {
string formattedDate = Strings.Format(Convert.ToDateTime(value), style);
return formattedDate;
} else {
return blankDate;
}
}
Where value is your: 10/22/2014 12:00:00 AM and style is :"MM/dd/yyyy" or something as you want
Related
I need to order my DynamicQuery by the number of day on a DateTimeColumn (Contact_ table by the way)
the default orderByComparator bring:
1969/04/02
1970/04/01
1970/04/01
1970/04/11
but I need
1970/04/01
1970/04/01
1969/04/02
1970/04/11
I tried overriding OrderByComparator and then using him on my dynamicQuery() method, but doesn't work
Tried to implement OrderByComparatorFactory myself but my compare method isn't called
I thing I can use a custom query, but there's no other way to do it?
by the way, I'am using a search container
DynamicQuery does not use compare method from an OrderByComparator method. DynamicQuery adds only the fields and asc/desc from the OrderByComparator.
See the Liferay code here:
BasePersistentImpl:
public List findWithDynamicQuery(
DynamicQuery dynamicQuery, int start, int end,
OrderByComparator orderByComparator)
throws SystemException {
OrderFactoryUtil.addOrderByComparator(dynamicQuery, orderByComparator);
return findWithDynamicQuery(dynamicQuery, start, end);
}
OrderFactoryUtil:
public static void addOrderByComparator(
DynamicQuery dynamicQuery, OrderByComparator obc) {
if (obc == null) {
return;
}
String[] orderByFields = obc.getOrderByFields();
for (String orderByField : orderByFields) {
if (obc.isAscending(orderByField)) {
dynamicQuery.addOrder(asc(orderByField));
}
else {
dynamicQuery.addOrder(desc(orderByField));
}
}
}
You may sort the result list by your comparator, as I did it in this example:
github
we tried to validate a javafx datepicker. So we use:
if (fromDatePicker.getValue() == null) {
sb.append("No valid from date!\n");
} else {
System.out.println(fromDatePicker.getValue().toString());
if (!DateUtil
.validEnglishDate(fromDatePicker.getValue().toString())) {
sb.append("No valid from date. Use the format yyyy-MM-dd.\n");
}
}
But at the moment it's impossible to get an invalid Date with the datepicker, because all invalid date's are changed to the start value.
So we asked us is it possible to get an invalid Date with the javafx datepicker?
***** EDIT *****
Example: we have the following datepicker:
DatePicker[2015-05-12]
now we entered "fjdfk" in the DatePicker so we have:
DatePicker[fjdfk]
on save the data's the datepicker changes automatical to DatePicker[2015-05-12]
You could use the DatePicker#setConverter(StringConverter<LocalDate>) to catch any parse exception and warn the user in consequence. Here is a sample :
public class SecureLocalDateStringConverter extends StringConverter<LocalDate> {
/**
* The date pattern that is used for conversion. Change as you wish.
*/
private static final String DATE_PATTERN = "dd/MM/yyyy";
/**
* The date formatter.
*/
public static final DateTimeFormatter DATE_FORMATTER =
DateTimeFormatter.ofPattern(DATE_PATTERN);
private boolean hasParseError = false;
public boolean hasParseError(){
return hasParseError;
}
#Override
public String toString(LocalDate localDate) {
return DATE_FORMATTER.format(localDate);
}
#Override
public LocalDate fromString(String formattedString) {
try {
LocalDate date=LocalDate.from(DATE_FORMATTER.parse(formattedString));
hasParseError=false;
return date;
} catch (DateTimeParseException parseExc){
hasParseError=true;
return null;
}
}
}
From your control, you'll just have to call converter#hasParseError(), converter being the one you set with DatePicker#setConverter(StringConverter<LocalDate>)
I have an Odata service which exposes an EF6 code first model. Some of these entities include DbGeography fields. I can GET these field, despite the DbGeography fields having quite an ugly serialized format, but I cannot figure out how to POST or PUT an entity to the service. The DbGeography type seems to struggle with deserialization.
Can anyone provide an example or link for how to do this?
I've had this problem too. Its a bug apparently.
Either two choices here - drop down to EF5 for the old System.Data.Entity.DbGeography (rather than System.Data.Entity.Spatial.DbGeography), or wait until they patch it.
Edit: Its been a long time, and so far the only hack I've come up with is this as a way to write to the properties and hide the ugly serialised format (however still cannot query against it.
private bool hasSetLongitude = false;
private bool hasSetLatitiude = false;
private double? longitude = null;
private double? latitiude = null;
/// <summary>
/// Get or set the coordinates.
/// </summary>
[Column("engi_coord"), Required]
public DbGeography Coordinates { get; set; }
/// <summary>
/// Get or set the lang coordinates.
/// </summary>
[Column("engi_lng"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public double? Longitude
{
get
{
return this.Coordinates != null ? this.Coordinates.Longitude : (double?)null;
}
set
{
this.longitude = value;
this.hasSetLongitude = true;
if (this.hasSetLongitude)
{
if (this.longitude.HasValue &&
this.latitiude.HasValue)
{
this.Coordinates = DbGeography.PointFromText(string.Format("POINT({0} {1})", this.longitude.Value, this.latitiude.Value), 4326);
}
else
{
this.Coordinates = null;
}
}
}
}
/// <summary>
/// Get or set the lat coordinates.
/// </summary>
[Column("engi_lat"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public double? Latitude
{
get
{
return this.Coordinates != null ? this.Coordinates.Latitude : (double?)null;
}
set
{
this.latitiude = value;
this.hasSetLatitiude = true;
if (this.hasSetLatitiude)
{
if (this.longitude.HasValue &&
this.latitiude.HasValue)
{
this.Coordinates = DbGeography.PointFromText(string.Format("POINT({0} {1})", this.longitude.Value, this.latitiude.Value), 4326);
}
else
{
this.Coordinates = null;
}
}
}
}
Migrate to add the computed columns:
this.Sql("ALTER TABLE dbo.engi_engineer ADD engi_lng AS engi_coord.Long");
this.Sql("ALTER TABLE dbo.engi_engineer ADD engi_lat AS engi_coord.Lat");
Now ignore the coordinates property from API:
this.EntityType.Ignore(p => p.Coordinates);
Well it has been over a year now and it doesn't look like this is getting fixed anytime soon. Especially with EF7 coming out very soon.
So, I would like to approach this another way.
What if the DbGeography type was not exposed as a property on the class and instead we expose a Latitude and Longitude property that are not mapped and then on their GET / SET we update the hidden DbGeography property?
I have tried this but have been unsuccessful with EF.
What you can do is inside the POST / PUT controller calls is use a stored procedure or SQL text to update the data.
If I find out how to get this to work with EF I will post here.
I currently use smartGwt (version 2.5) inside an other framework (Broadleaf).
When i set the locale to french :
Date fields are well formated (DD/MM/YYYY) and the calendar is translated in french but when i change the date and save the form a popup appear with the error message :"Doit être une date" (Must be a date in english). The validator expect a date with MM/DD/YYYY format.
Link to the class used by the framework to create the date field : https://github.com/BroadleafCommerce/BroadleafCommerce/blob/BroadleafCommerce-2.2.x/admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/client/datasource/dynamic/module/BasicClientEntityModule.java
I found a post with same problem (forums.smartclient.com/showthread.php?t=19847) but there is no answer.
Please, let me know how to solve this problem
EDIT :
What i have tried :
#Override
public void onModuleLoad() {
DateUtil.setShortDateDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
DateUtil.setShortDateDisplayFormatter(new DateDisplayFormatter() {
#Override
public String format(Date date) {
if(date == null)
{
return null;
}
else{
final DateTimeFormat dateFormatter = DateTimeFormat.getFormat("DD/MM/YYYY");
return dateFormatter.format(date);
}
}
});
Because the code below is not allowed :
DateUtil.setShortDateDisplayFormatter(DateUtil.TOEUROPEANSHORTDATE);
I put my code during the application initialization but the problem still present :-(
Screenshot : http://www.hostingpics.net/viewer.php?id=989088date.png
Do you have an other idea?
Set date formatter of the field to DateDisplayFormat.TOEUROPEANSHORTDATE.
dateItem.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
Also check display seconds in DateTimeItem (SmartGWT) to find another way to set a custom formatted date string when dateItem.useTextField is true.
As the forum thread indicates, its also possible to set default date/datetime format for the application using methods of com.smartgwt.client.util.DateUtil, which should be used only once, during application initialization (e.g.- EntryPoint).
DateUtil.setShortDateDisplayFormatter(DateUtil.TOEUROPEANSHORTDATE);
Problem solved !
You have to use the code below during application initialization :
private static final String DATE_FORMAT = "dd/MM/yyyy HH:mm";
public void onModuleLoad() {
DateUtil.setShortDateDisplayFormatter(new DateDisplayFormatter() {
#Override
public String format(Date date) {
if(date != null)
{
final DateTimeFormat dateFormatter = DateTimeFormat.getFormat(DATE_FORMAT);
return dateFormatter.format(date);
}
return null;
}
});
DateUtil.setDateParser(new DateParser()
{
public Date parse(String dateString)
{
try{
if(dateString != null){
final DateTimeFormat format = DateTimeFormat.getFormat(DATE_FORMAT);
return format.parse(dateString);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
});
}
I'd like Play!Framework to convert a Timestamp sent via POST into a java.util.Date format in the Model, but I don't know if it's directly possible.
Here's my model :
public class Contact extends Model {
#Id
private Long id;
#Constraints.Required
private String name;
#JsonIgnore
#Temporal(TemporalType.TIMESTAMP)
private Date removed = null; // When the contact is no longer active
}
I tried to add #Formats.DateTime(pattern="?") to removed, but since DateTime use SimpleDateFormat, I wasn't able to found which pattern to use to convert a timestamp to the correct Date.
How can I do ?
Ok I'll answer myself on this, here's what I did (maybe not the best way to do it, but it works).
I don't use the Model to match the posted param to the removed value, but instead, I do this in my Controller :
String[] accepts = {"name", "datestamp"};
Form<Contact> form = Form.form(Contact.class).bindFromRequest(accepts);
Date date = null;
try {
date = new Date(Long.parseLong(form.field("datestamp").value()));
}
catch (NumberFormatException nfe) {}
if (date == null) {
form.reject("date", "error.invalid");
}
if (form.hasErrors()) {
return badRequest(form.errorsAsJson());
}
else {
Contact contact = form.get();
contact.setRemoved(date);
contact.save();
return ok();
}