Date field is not displayed when DateFormat is dd.MM.yyyy and dd is bigger than 12 - asp.net-mvc-4

In my view model i have several DateTime fields. I've decorated them with DisplayFormat attribute to give them date time format:
public class MyModel{
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime? ReceivedDate{get;set;}
//omitted for brevity
}
This is the View:
<div>#Html.DisplayFor(x=>x.ReceivedDate)</div>
Now when date is say 12 July 1985, it'll display 07.12.1985 (Day and month swapped). But if I set date to for example 13 July 1985 , it'll be just blank. So apparently MVC tries to match the entered date to some other format.
P.S. I first insert the model to database and then read the recently added model on another view.

I've found the problem that caused this issue. In my web.config file, there was the following entry:
<system.web>
<globalization enableClientBasedCulture="true" culture="auto:en-US" uiCulture="auto:en-US" />
</system.web>
So this was setting the current culture to US. After removing that entry the problem got solved. BTW, you can just set your desired culture instead of removing too.

Related

Why are the minutes disabled in vue-ctk-date-time-picker?

I am using the vue-ctk-date-time-picker to display a date time picker modal where users can pick date and time. I use a minDate such that users cannot pick date and time less than the current date and time. This works perfectly with format YYYY-MM-DD HH:mm:ss, but I needed the AM and PM format so I changed the format to YYYY-MM-DD HH:mm a. Now, the PM equivalent of the AM date is also being disabled.
For example, its 8:30 AM, so the picker disables all minutes upto 30 and users can only select 31, 32 and so on. But if I select PM, the minutes are still disabled, ie, the users are only able to pick from 31, when its not even PM yet.
Has anyone faced this problem? Is there a problem with package itself?
For anyone else having this problem, this is the solution according to the document here: https://github.com/chronotruck/vue-ctk-date-time-picker#behaviour
In order to avoid having too much properties in the component, We're
adding a behaviour property that is an object including some annex
behaviour values.
The default value for this object is:
{
time: {
nearestIfDisabled: true;
}
}
To override those values, pass a new object with the values you want
to override:
<ctk-date-time-picker
:behaviour="{
time: {
nearestIfDisabled: false
}
}"
/>

Send UTC timestamps with moment.js to ASP.NET Core controller

I have a database with measured values from devices that I want to display in a web frontend. First I send the list of devices to the frontend together with the IANA timezone specifier for each device.
I would like all timestamps to be exchanged as UTC. The user selects a time range in the frontend in device-local time. I use moment.js to convert these timestamps to UTC with the known timezone of the device like this:
var startTimestamp = new Date(2017, 7, 1); //some local timestamp (zero-based month!)
var m = moment.tz(startTimestamp, "Europe/Berlin");
var utc = moment.utc(m).format();
utc is now "2017-07-31T22:00:00Z" which seems to be correct given the 2 hours offset for Berlin in DST.
I send this utc timestamp to my ASP.NET Core backend. The controller looks like this:
[HttpGet]
public IEnumerable<TimestampedValue> GetValues(int id, DateTime startTimestamp)
{
...
}
The problem is that startTimestamp is 2017-08-01 00:00:00 when the controller is called and its Kind property is set to Local. I would have expected it to be the same UTC timestamp.
Any idea what I'm doing wrong? I think moment.js is doing its job correctly so this must be a problem on the server side. If I recall correctly, the deserialization is done by JSON.net but I don't understand why it does not respect the Z at the end of the time string.
After #dbc pointed me to the different behavior between GET and POST requests I come to this conclusion:
Since my request uses the GET method and query strings are not JSON, there is no JSON.net involved in the problem, it is the default .NET Core DateTimeConverter that does the conversion. Moment.js correctly converts the timestamp to a UTC string, I checked that using the browser developer tools.
The code for DateTimeConverter can be found here:
https://github.com/dotnet/corefx/blob/312736914d4e98c2948778bacac029aa831dd6b5/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs
As can be seen there, the converter uses DateTime.Parse. It can be tested in a simple test project that DateTime.Parse does not respect the Z-suffix. This is also discussed here DateTimeConverter converting from UTC string.
I think there would be at least four solutions
1) write a custom model binder. These SOs each show a part of it Custom DateTime model binder in ASP.NET Core 1 (RTM)
https://dotnetcoretutorials.com/2016/12/28/custom-model-binders-asp-net-core/
2) write a custom type converter that overrides the default DateTime converter and checks whether there is a trailing Z. If so, use DateTime.Parse with the DateTimeStyles.AdjustToUniversal. Else fall back to the default implementation. I like this solution but I currently don't know how to replace the default DateTimeConverter.
3) replace all relevant DateTime parameters in the controllers with DateTimeOffset. DateTimeOffset seems to correctly convert the UTC string.
4) use a POST instead of a GET request with JSON in the request body. JSON.net seems to correctly convert the UTC string.
My preferred solution is currently a mixture of 3 and 4, depending on the context.

Error Converting DateTime using format

I get the following error when trying to import a CSV file.
Error Converting '2007/01/02' to type: 'DateTime'. Using the format: 'yyyy/MM/dd'
I have set the class like this:
[FieldConverter(ConverterKind.Date, "yyyy/MM/dd")]
public DateTime PriceDate;
Any idea why that could be, since the format matches - it is the second of Jan 2007?
When I change the date format to 2007.01.02 then Filehelpers parses perfectly.
I use V 3.1.5.0
Thanks
Try changing the mask to:
[FieldConverter(ConverterKind.Date, "yyyy/M/d")]
public DateTime PriceDate;
Click on the 'Converters' tab in this link to learn more about a handful of datatypes available, such as numeric and dates.

How do I change the format ActiveRecord expects when parsing dates from a text field in a form?

The problem
I have a Ruby on Rails model with a Date attribute.
In the form for this model, I am using a single text field with a JQuery datepicker to represent this attribute (not a drop down for each of year, month, and day, as is the Rails custom).
The datepicker inserts dates with a mm/dd/yyyy format.
Rails is expecting dates with a dd/mm/yyyy format.
Examples
If a user selects March 12th, 2012, the datepicker puts 03/12/2012, which is interpreted by Rails as December 3rd, 2012.
If a user selects March 20th, 2012, the datepicker puts 03/20/2012, which is interpreted by Rails as the 3rd day of the 20th month of 2012. Since this date doesn't exist, Rails casts this to a nil value (I think).
Question
How do I change the date format Rails uses when parsing this date text field?
Notes:
1) I do not want to change the format of the date the datepicker inserts into the text field,
2) I am not asking about displaying my date attribute in a view.
I initially thought this could be solved through the Rails internationalization features, but it turns out I was wrong.
Ever since Ruby 1.9, the standard format for date parsing is dd/mm/yyyy, so as to better accomodate international users. More details can be found in this SO answer.
That standard is maintained in Rails, as Date.parse is now used to process data from form inputs. Using a before_validation callback won't work because the field is going to be received as nil by the callback method.
Right now there are two gems dealing with this specific issue, namely that date parsing in Rails does not follow the locale settings from I18n.locale. Both seem to work well.
delocalize, by clemens - Seems to have been applied successfully in a decent number or projects and has the highest number of stars at the moment.
i18n_alchemy by carlosantoniodasilva - This one has been released more recently. The author is a Rails core team member, and a very active one at that. Definitely deserves a look.
Since you don't want to change the picker's format, I would suggest you use a hidden field for the actual model property.
For example, add a hidden field for the model's date property, assuming you use a form builder as usual:
f.hidden_field :date
Then for the picker text input, don't bind it to the model's date property. Let's say the hidden field has ID 'modelname_date' and the picker text input has ID 'date_picker', use the following to make it work:
$(function(){
$("#date_picker").datepicker({altField: '#nodelname_date', altFormat: 'dd/mm/yyyy'});
});
In this way the date picker shows the date as 'mm/dd/yyyy' but Rails will see the date as 'dd/mm/yyyy'.
Update:
If you want to work this out on the Rails side, here's another solution I'd suggest:
Add a virtual property to your model: attr_accessor :bad_format_date
Add a before_validation callback in which you parse the input date and assign it to the real field:
before_validation do
self.date = Date.strptime(bad_format_date, "%m/%d/%Y")
end
Then for the form on the view use bad_format_date but initialize it with the date field value (if it's an edit form).
The timeliness gem makes ruby date/time parsing much more customizeable and integrates well with Rails.
Since you're working with Rails, be sure to check out the validates_timeliness project as well by the same guy. It includes all of timeliness plus sophisticated date/time validation methods for ActiveModel.
You could try do something like this.
$(function(){
$('#date_picker').datepicker( {
beforeShowDay: $.datepicker.noWeekends,
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: 'dd-mm-yy',
defaultDate: date,
gotoCurrent: true
});
I just add the following monkey patch to config/time_formats.rb
class Date
class << self
alias :euro_parse :_parse
def _parse(str,comp=false)
str = str.to_s.strip
if str == ''
{}
elsif str =~ /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2,4})/
year,month,day = $3.to_i,$1,$2
date,*rest = str.split(' ')
year += (year < 35 ? 2000 : 1900) if year < 100
euro_parse("#{year}-#{month}-#{day} #{rest.join(' ')}",comp)
else
euro_parse(str,comp)
end
end
end
end

Custom DateTimePicker value isn't saved in Application Settings

UPDATED :
I want to save a Custom DateTimePicker.Value in my Application Settings.
The custom format is : dd/MM/yyyy hh:mm:ss, instead of dd/MM/yyyy
The field i've created in the application settings parameters is LASTSAVE (DATE / APPLICATION)
When I try to link in the ApplicationSettings/PropertyBinding ... VALUE with my field LASTSAVE, i have an error :
The Value '01/01/0001 00:00:00' is not valid for 'Value'. 'Value' must
be ... 'MinDate' et 'MaxDate'.
Name of the parameter : Value
I then entered the MIN and MAX date in the properties of my control DATETIMEPICKER.
I have also put into the properties Value a start date like 23/11/2011 12:00:00 ;
However, when i retry to link in the ApplicationSettings/PropertyBinding ... value to LASTSAVE / I have the same error (The Value '01/01/0001 00:00:00' is not valid for 'Value'. ). I've saved all, do a process that put a value in the datetimepicker.value, but it's not saved, cause not linked.
A solution please ?
'01/01/0001 00:00:00' is DateTime.Empty, the default value for a DateTime that hasn't been set. Is there a value in your application settings to begin with? Are you handling the case where the value has not yet been set?