Given this VM
public class ApplicationDTO : BaseDTO
{
public DateTime Date { get; set; }
public int JobId {get;set;}
public int Status {get;set;}
[Required]
public string Message { get; set; }
public string ExpertCode { get; set; }
}
I have a hidden field thusly
#Html.Hidden("Date", DateTime.Now)
Which fiddler shows me is sent to the server as I would expect (UK format, I'm in the UK!)
But on the controller the date shows as being the default min. date
Is it just the UK format? If so, what is my best way round it? Whilst currently I am setting it to the current date, potentially it could be set to any given date i.e.
#Html.HiddenFor(x => x.Date)
I am using AJAX to submit the form, if that makes a difference.
If it is a Get MVC uses culture invariant format (Basically US format) by default during model binding. So it doesn't accept UK date format. I believe the design reasons are that a querystring could be passed around so therefore it needs to be culture invariant (I wasn't 100% convinced by that logic).
This article covers a possible solution http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/
We just make sure we never do a Get with a UK date format
This questions also covers the issue Globalization problem with DateTime and ASP.NET MVC 3 Model Binding
you should use Data Annotation for Formatting the date on your Model or View model
public class ApplicationDTO : BaseDTO
{
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime Date { get; set; }
public int JobId {get;set;}
public int Status {get;set;}
[Required]
public string Message { get; set; }
public string ExpertCode { get; set; }
}
Apply the format according you.
As i have seen you are not providing any format to your property
I had a similar issue with dd.MM.yyyy format and had to set globalization element in web.config to appropriate culture and uiCulture attribute settings.
If you use #Html.Hidden (not the For helper) it won't be able to match the parameter in the request to the property in your model.
If you use #Html.HiddenFor(x=>x.Date, "28/2/2013") you will see the date populated appropriately.
Also you can verify the Request.Params collection. Put a break point in the Action. You'll see that one of the Params has your date.... JQuery does not affect this in any way.
Related
I'm working on Angular (front-end) with C# (back-end) project going, and I'm going to use the input time <input type="time">
So, is the value a string, or should I save it as DateTime and get the time part only?
How should the property be on the backend and database?
public DateTime? Property { get; set; }
Or
public string Property { get; set; }
Save to Database in DateTime, do all business logic in DateTime, but when you want to display to view, it is smooth to convert to string. Bellow is a sample code that i use to help with this.
public string DateTimeToString(DateTime dateTime)
{
var stringDate = dateTime.ToString("dddd, dd/MM/yyyy HH:mm");
return stringDate;
}
You can format it however you wish, this will help to keep your DateTime on tables to look uniform, and removes the need to always convert to string at the presentation layer.
I use NLog for logging in one of my applications and wanted to provide logs to the user via the UI. I have built a log parser for this purpose that takes the log file and parses all the logs into C# objects that are then sent to the UI so the user can view them.
However, I am having a hard time getting the date parsing right. NLog logs with log4jxmlevent look like the following:
<log4j:event
logger="Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker"
level="INFO"
timestamp="1539939614029"
thread="6">
<log4j:message>Executing action method Condato.IoT.Client.TinkerForge.Controllers.ApplicationController.GetLogs (Condato.IoT.Client.TinkerForge) - Validation state: Valid</log4j:message>
<log4j:properties>
<log4j:data name="log4japp" value="Condato.IoT.Client.TinkerForge(15096)" />
<log4j:data name="log4jmachinename" value="DEVDOTNET" />
</log4j:properties>
</log4j:event>
I then have created a simple class to hold a log:
public class Log
{
public string Logger { get; set; }
public string Level { get; set; }
public DateTime Time { get; set; }
public string Message { get; set; }
public string LogSource { get; set; }
public string LogSourceName { get; set; }
}
After that I simply iterate over my logs and parse each one from XML to C# objects. The relevant part here is parsing the timestamp property of each log.
var time = new DateTime(long.Parse(rootReader["timestamp"])).ToUniversalTime();
I assumed that the number in the timestamp property represents the ticks. So I just passed them into the Date() constructor. However, this is the output I get from parsing the timestamp property:
So this seems not right as those logs were created yesterday. I have looked at the NLog documentation, but log4jxmlevent is very sparsely documented or I missed something.
It turns out that the timestamp property is a Unix time stamp. So I needed to parse it like this:
var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(rootReader["timestamp"].ToString())).DateTime;
It then gave me the correct value.
I have a date picker in html which is bound to a Date property of an employee.
ex: i have selected the date as "Thu Feb 22 2018 00:00:00 GMT+0530 (India Standard Time)".this is the value i get when i log in console.
But when i tried to debug in C# the value is changed.
{21-02-2018 18:30:00}
How to handle or work with the typescript date object when passing it to a API method and displaying it back
My typescript Model
export class Visitor {
public id: number;
public firstname: string;
public lastname: string;
public dob: Date;
public genderId: number;
public age: number;
}
and C# model
public class Visitor
{
public int Id { get; set; }
public string Lastname { get; set; }
public string Firstname { get; set; }
public int Age { get; set; }
public DateTime DOB { get; set; }
}
As long as you are passing a valid Date object you should be fine.
Your problem probably lies in your Culture settings in .NET side.
Can you please try doing this in your controller action:
var culture = new CultureInfo("gu-IN");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
Since you provide no code, this is merely a guess.
When you are printing in console, browser is printing the date in local timezone which is India in your case. When you are retrieving the value on server, C# is treating date in UTC. That is why you see a difference of 5.30 hours. India time is UTC + 5.30 Hours.
If you are storing the date value in UTC format on server side then convert the value of date object from client side to UTC using the libraries such as momentjs.
While retrieving the value from server, send the UTC value from server and convert it to local time zone using libraries such as momentjs. I think this strategy will work.
I have a test class and an ExecutionDate property which stores only date but when we use [DataType(DataType.Date)] that also stores the time portion in database but I want only date portion.
public class Test
{
[Key]
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime ExecutionDate { get; set; }
}
Is any way to store only date on time portion in db using Entity Framework? Please help me....
I have added snapshot when use [DataType(DataType.Date)] that stores time portion 00:00 I want remove that
I think you are trying to specify database column type. You could use data annotations as described in this article.
Here is an example :
[Table("People")]
public class Person
{
public int Id { get; set; }
[Column(TypeName = "varchar")]
public string Name { get; set; }
[Column(TypeName="date")]
public DateTime DOB { get; set; }
}
By default, string is translated to nvarchar, we have changed that here. Also Datetime (this is what you asked I suppose) which by default maps to datatime in sql server, is changed to date which stores only the date portion and not the time portion of a DateTime value.
On EF core one may add override OnModelCreating in DbContext class.
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Test>().
Property(p => p.ExecutionDate)
.HasColumnType("date");
}
As David said above, once you bring that data into the application it will be a DateTime with the timestamp added onto the date. This would be the same result too if you stored the date as a string and used Convert to change to a DateTime for any manipulation:
string date = "2015-11-17";
var dateTime = Convert.ToDateTime(date);
Unless you want to manipulate strings in your application to avoid the timestamp, you can only work with DateTime. For display purposes though, you can always format the date and remove the timestamp:
var dateTime = DateTime.Now;
var formatDate = dateTime.ToString("yyyy-MM-dd");
In .NET 6 now you have new special type - DateOnly
More info here:
https://github.com/dotnet/efcore/issues/24507
https://www.stevejgordon.co.uk/using-dateonly-and-timeonly-in-dotnet-6
Change datatype on the database from Datetime to Date type
Is it really an issue for you anyway? You may want time in there at some point,
Change DateTime to nvarchar(10) in database
if u use DateTime in database 00.00.00 will be automatically assigned by database
string date = DateTime.Today.ToShortDateString();
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.