How to store the datepicker value into the table? - datetimepicker

Datetime date = Convert.ToDateTime(fmcollection[""]); I have to use to convert the datetime but that line hit the error Cannot implicitly convert type 'System.DateTime'
public ActionResult save( FormCollection fmcollection)
{
Datetime date = Convert.ToDateTime(fmcollection[""]);
/* insert code */
}

Related

Date binding dd-mm-yyyy in ASP NET Core 3.1

Im trying send date in format dd/mm/yyyy as query string parameter but binding for date property not working for me, only if I send date US format mm/dd/yyyy , any idea how to solve?
Generally, we solve this situation by using Custom model binding.
You can see my code example below.
Action:
[HttpGet]
public object Demo([ModelBinder(BinderType = typeof(DateTimeModelBinder))] DateTime MyTime)
{
return Ok();
}
DateTimeModelBinder:
public class DateTimeModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var valueProviderResult = bindingContext.ValueProvider.GetValue("MyTime");
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
var value = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
var TestTime = DateTime.ParseExact(value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
bindingContext.Result = ModelBindingResult.Success(TestTime);
return Task.CompletedTask;
}
}
Url:https://localhost:xxxx/api/xxx/?mytime=19/05/2020
Result:
Another solution would be to send your date in UTC format. For example:
"2020-11-19T10:21:05Z"
Then ASP.Net Core will bind it automatically. Using UTC format is also considered a good practice. You easily cast your date object to UTC string using
string foo = yourDateTime.ToUniversalTime()
.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");
Source
Or in JavaScript
new Date('05 October 2011 14:48 UTC').toISOString();
Source

Allow specific datetime formats in asp.net core app on json deserialization

I want to allow specific datetime formats in my asp.net core app.
I have this code in Startup.cs on ConfigureServices method:
...
services.AddMvc()
.AddJsonOptions(options =>
{
...
options.SerializerSettings.DateFormatString = "dd/MM/yyyy HH:mm";
})
...
This property allow only one datetime format.
I'm needing something like this (with many datetime formats permitted):
...
services.AddMvc()
.AddJsonOptions(options =>
{
...
options.SerializerSettings.DateFormatString = { "dd/MM/yyyy HH:mm", "dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy", ... };
});
...
Thanks.
This is not possible. Logically, how would the serializer know which format to actually apply? There's no Date type, so a DateTime, even if it no time component is set is still a DateTime and will simply return the time as midnight (00:00:00).
You're struggling here with a basic flaw in API design. An API should not return different types for the same member(s). If time is a component ever, then time should always be present, even if it's zeroed out. Returning different responses puts additional and sometimes impossible burdens on the client.
From https://learn.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support:
public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Debug.Assert(typeToConvert == typeof(DateTime));
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
class Program
{
private static void ProcessDateTimeWithCustomConverter()
{
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new DateTimeConverterUsingDateTimeParse());
string testDateTimeStr = "04-10-2008 6:30 AM";
string testDateTimeJson = #"""" + testDateTimeStr + #"""";
DateTime resultDateTime = JsonSerializer.Deserialize<DateTime>(testDateTimeJson, options);
Console.WriteLine(resultDateTime);
string resultDateTimeJson = JsonSerializer.Serialize(DateTime.Parse(testDateTimeStr), options);
Console.WriteLine(Regex.Unescape(resultDateTimeJson));
}
}
This should handle any unambiguous date/time.

CalendarDatePicker returns null when selecting the same date second time

I'm using CalendarDatePicker binded to Property, and the Closed event binded to a method, both in my ViewModel. The LoadPage method uses SelectedDate property to load some data. Everything is working fine except for the time when i try to pick the same date that is picked already. In the converter i can see that the value picked is null and i get an exception because it cannot cast null to DateTimeOffset. Any idea why picked date end up being null? And how to fix this issue?
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
var dateoffset = (DateTimeOffset)value;
return dateoffset.Date;
}
...
<CalendarDatePicker x:Bind ViewModel.SelectedDate,
Converter={StaticResource DateTimeConverter}, Mode=TwoWay}"
Closed="{x:Bind ViewModel.LoadPage}">
</CalendarDatePicker>
I have fixed it by checking in converter for null and returning DateTime.MinValue value, and then in property setter raising PropertyChanged event.
It is not really nice, i would welcome better solution.
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value == null) return DateTime.MinValue;
DateTimeOffset sourceTime = (DateTimeOffset)value;
DateTime targetTime = sourceTime.DateTime;
return targetTime;
}
public DateTime CurrentDate
{
get { return _currentDate; }
set
{
if (value == DateTime.MinValue)
{
RaisePropertyChanged(nameof(CurrentDate));
return;
}
Set(ref _currentDate, value);
}
}

What is the input pattern for org.sql.Date

On a Website, i want a field that gets a Date as Input and then save that date in a "Attendee"-Class.
public class Teilnehmer {
private Date jahrgang = null;
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
#Column (name="ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column (name="Jahrgang")
public Date getJahrgang() {
return jahrgang;
}
public void setJahrgang(Date jahrgang) {
this.jahrgang = jahrgang;
}
That attribute 'jahrgang' has the Type org.sql.Date. Now, it doesn't matter what i put into that text field, when i send the form, it reloads the page and returns the already filled field and marks the Date-field red. It looks kinda like this:
What is the input type in this case?
EDIT:
I don't get any unusual Log outputs when i send the form.
part of the form where i input:
<p:outputLabel for="eintritt" value="Eintritt: "/>
<h:inputText name="eintritt" id="eintritt" value="#{AdminAdd.teilnehmer.eintrittsdatum}"></h:inputText>
<p:watermark for="eintritt" value="Eintritt"></p:watermark>

Change the Date Default Format in Jettison

Can the Default Date format returned by Jettison Library can be changed ?
This is the default Date format
{
"post": {
"activityDate": "2012-07-03T16:15:29.111-04:00",
"modfiedDate": "2012-07-03T16:15:29.111-04:00",
"createdDate": "2012-07-03T16:15:29.111-04:00"
}
}
can that be changed ?
We can do this in Jakson using org.codehaus.jackson.map.JsonSerialize annotation.
How to do this in Jettison ?
Is there any similar class in Jettison ?
Thanks
This is can be done using XMLAdapters
public class DateAdapter extends XmlAdapter {
/**
* This method is called when we return the DTO Date property to UI, We
* convert the date to UI date format
*/
#Override
public String marshal(Date inputDate) throws Exception {
.........
return dateStr;
}
/**
* This method is called when UI sends date String and we set the DTO Date
* property
*/
#Override
public Date unmarshal(String inputDateStr) throws Exception {
................
return inputdate;
}
}