DisplayFormat with CultureInfo DateTime - c#

I'm trying to get set the DisplayFormat of a public property to the current cultureinfo datetime format. The class will be used for Silverlight Datagrid.
[DisplayFormat(DataFormatString=CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]
public DateTime createDate { get; set; }
It says, only that the argument can only be constant and typeof parameter...
Any ideas?
UPDATE, I tried Lukazoid solution but the Silverlight datagrid ignores the data annotations. The datagrid colums are added in codebehind because of localization.
The column looks like this:
DataGridTextColumn tcCreateDate = new DataGridTextColumn();
tcCreateDate.Header = SilverlightApplication.Resources.ContentGrid.dgCreateDate;
tcCreateDate.Binding = new Binding("createDate");

Attribute values must be constant or a result of the typeof syntax.
If you want to use the short date format for the current culture, use the following format string:
[DisplayFormat(DataFormatString = "{0:d}")]
Update
I can see your updated code to add the DataGridTextColumn, try this to add the StringFormat:
DataGridTextColumn tcCreateDate = new DataGridTextColumn();
tcCreateDate.Header = SilverlightApplication.Resources.ContentGrid.dgCreateDate;
tcCreateDate.Binding = new Binding("createDate") { StringFormat = "{0:d}" };
By default, silverlight uses en-US as the current culture for all bindings (regardless of your system settings), this means the StringFormat will result in a US format of the date. See here for a solution to ensure your current settings are taken into account.

Tried like this
public class Foo
{
[DataType(DataType.DateTime)]
public DateTime createDate { get; set; }
}
This will display with the date base culture of your project

Related

mvc view date display format

I have my date data annotation as
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreatedOn { get; set; }
In my view:
#Html.DisplayFor(item=> item.CreatedOn)
But my date appears as just: 11 12 2017 in my view, insteaed of 11/12/2017. What ate my /'s? Anything I forgot to include?
In the format-string, wrap the / in single quotes, so your model should look something like this:
[DisplayFormat(DataFormatString = "{0:dd'/'MM'/'yyyy}")]
public DateTime CreatedOn { get; set; }
When rendered on the page, it uses the desired format.
The Documentation on DataFormatString has a remark about formatting of dates, but doesn't mention anything about this issue of formatting forward-slashes. Their proposed solution about setting HtmlEncode = true didn't work for me. I found the solution in the alternative suggestion on the answer for this similar question.
It seems everything boils down to Culture info. As it currently stands it doesn't seem like we can specify CultureInfo in DisplayFormat, so i ended up defining a reusable helper method:
public static string FormatDate(this IHtmlHelper helper, DateTime date)
{
var formattedDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", date);
return formattedDateWithTime;
}
and in my view:
#Html.FormatDate(Model.CreatedOn)

ASP.NET MVC How to handle dynamic datetime format from database

In my ASP.NET MVC 5 dwith EF 6 project, I have a database where datetime format is stored as string like "dd-MM-yyyy". User can change this format any time. User will use the given format in the date fields in the view. But when they will post that. Automatically it will bind as a DateTime for that property. I am statically handling it by the following code
[DataType(DataType.Time), DisplayFormat(DataFormatString = "{HH:mm}", ApplyFormatInEditMode = true)]
public DateTime? EndingTime { get; set; }
public string EndingTimeValue
{
get
{
return EndingTime.HasValue ? EndingTime.Value.ToString("HH:mm") : string.Empty;
}
set
{
EndingTime = DateTime.Parse(value);
}
}
but I know it's not a best way to do that. There may need a model binder or filter or any kind of custom attribute. I will be greatly helped if you give me a efficient solution with sample code. Thanks in advance.
NB: I am using razor view engine. and my solution consists of 7 projects. So there is no chance of using Session in model. Again I have a base repository class for using entity framework.
People usually store the datetime in the database as a datetime.
Then wherever you do a translation from datetime to string that datetime can be displayed in a format that depends on the culture of the viewer.
By doing this you can quickly make a page with datetime formats that will format the datetimes nicely wherever you are.
change the culture you pass to the toString and the format changes.
please see this MSDN page for more info about it.
edit: (see comments below)
anywhere on server:
string WhatYouWant = yourTime.ToCustomFormat()
and create an extension method for the datetime that gets the format out of the database and returns a string in the correct format.
public static class MyExtensions
{
public static string ToCustomFormat(this DateTime yourTime)
{
// Get the following var out of the database
String format = "MM/dd/yyyy hh:mm:sszzz";
// Converts the local DateTime to a string
// using the custom format string and display.
String result = yourTime.ToString(format);
return result;
}
}
This will allow you to call it anywhere anytime on your server. You can't access the method client side in javascript. I hope this helps.
(To be honest I'm a new developer too and still have a lot to learn ^^)
I have tried many options regarding this problem. Now what I am doing is created an action filter to catch all the DateTime and nullable DateTime Fields. Here I am providing the binder.
public class DateTimeBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
DateTime date;
var displayFormat = SmartSession.DateTimeFormat;
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,"Invalid Format");
}
return base.BindModel(controllerContext, bindingContext);
}
}
in views the code I am formatting the date using same date format.

how to format a date inside a collection of objects using linq in c#

I have a list of objects in my collection and need to format the date on an object date property (NoteDate) to show dates in the format like "dd'/'MM'/'yyyy HH:mm:ss" whereas in database the format of the date is like '2015-02-19 00:00:00.000'. Below is my object
public class Note
{
public int Id { get; set; }
public string NoteText { get; set; }
public DateTime? NoteDate { get; set; }
}
and I populate the collection as below
var notesList= _uow.Find<Note>(n => n.FK == leadId).ToList();
how can we write the query to get the desired date format?
thanks
You are, properly, storing the date in a DateTime? object. DateTime is simply a storage mechanism.
What you are really interested in is how to display the DateTime in some UI.
So here's the steps your Date/Time is going to take:
Get returned as query content from the database
Get stored in the DateTime property
Be shown to the user
To format a value from a DateTime object there are several options - check out the methods on the DateTime class.
Your dates will be represented as a DateTime instance .. how .NET decides to represent dates.
When you're displaying them to your user/using them for display somewhere, you can simply format them at that point. For example:
var notesList = _uow.Find<Note>(n => n.FK == leadId).ToList();
var thirdNoteDateString = notesList[2].NoteDate.ToString("dd MM yyyy");
Or, perhaps in a Razor view (if this was an MVC application):
#foreach (var n in Model.Notes) {
<p>#n.NoteDate.ToString("dd MM yyyy")</p>
}
Hopefully that shows the difference. How the date is presented is up to you when you decide to present it.
you should not modify the content of your buisness object just for a Show purpose,
You should use a converter or a StringFormat like :
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
see this question for more info

format datetime object inside ajax.actionlink

I have a view where there are ajax.actionlinks, some of these action links need to display a date property of the model and I have the date property as follows:
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Date { get; set; }
however, because ajax.actionlink accepts a string for its first argument, I can't use a lambda expression :
m => m.Date
rather I'm using
Model.Date.ToString()
but this isn't showing the formatting I want. I've tried doing
Model.Date.ToString("MM-dd-yyyy");
but I'm getting red underline because its not recognizing the ToString overload with 1 argument... any ideas on how I can get this to work?
Since Model.Date is nullable, you need to access the Value of the DateTime? before using that version of ToString:
Model.Date.HasValue ? Model.Date.Value.ToString("MM-dd-yyyy") : null;

How to validate DateTime inside TextBoxFor ASP.NET MVC

I have this code:
#Html.TextBoxFor(m => Model.MyDateTime)
MyDateTime - is DateTime object.
It shows correct date and time inside textbox: 09/10/2010 05:19:56 PM
But when I try to click submit button it shows that it is incorrect value. I use jquery.validate.unobtrusive.js file for validation.
The gist of the solution I pointed to in my comment is that you can use a specialized model for the view which contains a string representation instead of the DateTime type, which allows you to easily validate the value with RegularExpressionAttribute. When you receive this model on the server (as posted from the client), simply convert it to a corresponding database model.
public class ViewModel
{
[Required]
[RegularExpression("\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}:\d{2}")]
public string MyDateTime { get; set; }
public Model ToPoco()
{
return new Model {
MyDateTime = DateTime.Parse(this.MyDateTime, "MM-dd-yyyy H:mm:ss")
};
}
}
public class Model
{
DateTime MyDateTime { get; set; }
}
data annotation will work for you!
You could use dataannotaion for validate yor model field properly. Using such annatation you could manualy prvide format of date in your annotation passing string pattern to it. And in that case it will perefectly working with default mvc validation.

Categories