jqgrid form post to webservice datetime changed format - datetime

I'm not sure whether this is related to jqgrid or is a webservice/postback/JSON issue, but I'll try to give as much information as I can.
I am posting the jqgrid's modal popup with the DateTime field .
When it posts back from the browser it submits the following data (as seen in Firebug):
InStock Yes
Name Desktop Computer
Note note
Ship 4
ShipDate 05-11-2013
id 1
oper edit
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UpdateOrder(DateTime ShipDate, string Name, Stock InStock,Ship Ship, string Note,int id)
{
return "";
}
The colModel of jqgrid looks like ..
colModel:[
{name:'Id',index:'Id', width:60, sorttype:"int", editable: false},
{name:'ShipDate',index:'ShipDate',width:90, editable:true, sorttype:"date",unformat: pickDate},
{name:'Name',index:'Name', width:150,editable: true,editoptions:{size:"20",maxlength:"30"}},
{name:'InStock',index:'InStock', width:70, editable: true,edittype:"checkbox",editoptions: {value:"Yes:No"},unformat: aceSwitch},
{name:'Ship',index:'Ship', width:90, editable: true,edittype:"select",editoptions:{value:"4:FedEx;1:InTime;2:TNT;3:ARAMEX"}},
{name:'Note',index:'Note', width:150, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}}
],
and the pickDate looks like
function pickDate( cellvalue, options, cell ) {
setTimeout(function(){
$(cell) .find('input[type=text]')
.datepicker({format:'dd-mm-yyyy' , autoclose:true});
}, 0);
}
Also the edit form style is as follows (when edit form shows up)
function style_edit_form(form) {
//enable datepicker on "sdate" field and switches for "stock" field
form.find('input[name=ShipDate]').datepicker({format:'dd-mm-yyyy' , autoclose:true})
.end().find('input[name=stock]')
.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');
However when the data is received at the server (asmx service), the datetime (ShipDate) changes to "11/05/2013 00:00:00" whereas the shipdate sent from the client is 05-11-2013 (which is correct). Any idea what's happening?

For datepicker you are using 'dd-mm-yyyy' format but on server side it converting to different format according to culture installed i.e. 'mm/dd/yyyy hh:mm:ss' with the time.
If you need the same format what you are passing from jquery you need to parse the date on server side in specified format.
DateTime time = Convert.ToDateTime("11/05/2013 00:00:00");
Console.WriteLine(time); //Default format
string format = "d/M/yyyy"; // Use this format
Console.WriteLine(time.ToString(format));

Related

How to force RFC3339 string for all datetime for queries upon display as API?

Using Cake 3.2.4
What am I getting now?
Whenever a query is executed and there is a datetime field, it will be displayed as RFC2822 string.
e.g. "2016-07-18T09:00:00+0800"
What do I want?
I want RFC 3339 string
e.g. "2016-07-18T09:00:00+08:00"
What did I try?
$paginationQuery->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$datetime = $row['start_date'];
$row['start_date'] = $datetime->format(\DateTime::RFC3339);
return $row;
});
});
I kinda forced the original datetime object to display as string.
Okay, so what's wrong?
I am unsure if it's wrong to do so. As you can see clearly, the original value for $row['start_date'] is actually a datetime object. Not a string.
Can I keep the value as datetime object but when it gets displayed as api, it uses the RFC3339 format?

$date not picking up current date - Sitecore

I am having an issue while setting default value for datetime field in sitecore standard values.
I know that $date takes the current date. If I specify $date in standard values for a date time field , it always takes the date as "1/1/0001".
How do I fix this ?
It is possible to enter tokens in the fields on the standard values, and then these will be replaced with other values, but only when a new item which use that template is created. It will not set date for the existing items which use this template.
$date is one of the token and it's replates with the system date (yyyyMMdd).
There is a blog post written by John West which explains how to Expand Standard Values Tokens in Existing Items with the Sitecore ASP.NET CMS.
EDIT:
Here is the code which is a part of MasterVariablesReplacer class which is used to replace $date token:
text = this.ReplaceWithDefault(text, "$date", (Func<string>) (() => DateUtil.IsoNowDate), context);
It is called from the ReplaceVariables processor, which is a part of expandInitialFieldValue pipeline (see /sitecore/admin/showconfig.aspx for all the expandInitialFieldValue processors).
You can try to add your own processor to this pipeline and see why the $date is not replaced properly:
public class ReplaceVariables : ExpandInitialFieldValueProcessor
{
public override void Process(ExpandInitialFieldValueArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
MasterVariablesReplacer variablesReplacer = Factory.GetMasterVariablesReplacer();
string text = args.SourceField.Value;
if (variablesReplacer == null)
args.Result = text;
else
args.Result = variablesReplacer.Replace(text, args.TargetItem);
}
}

ASP.NET MVC5 stores date in wrong format

last days I have a quite hard time to convince MVC5 project to work with dates as I would like to. After intensive googling I've tried numerous attepmts to make it work properly, but without success.
Here is the problem:
I need to display and edit dates on my webpage in format dd.MM.yyyy (i.e. 15.07.2015). For editing I also need to use jquery ui datepicker. The thing here is that I've been able to successfully set that datepicker to display date in requested format, also the jquery validation is now correctly validating the date in given format. So as for UI so far so good. The problem appeared in moment, when I clicked submit button - there was an error message like:
The value '15.07.2015' is not valid for Start Date.
After brief investigation I've found that when the date is passed to server it has switched format - instead of dd.MM.yyyy the date is treated like MM.dd.yyyy. In other words the error pops up only when the day part of date is higher than 12.
Here are some highlights from my code:
In my model for date I have this:
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[UIHint("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateStarts;
Which I believe is everything I need to do to make that date display in specified format and also force users to fill the textbox with date in right format.
As given in [UIHint("Date")], I have my own template for rendering textbox for editing date. The implementation of that template is following:
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
#Html.TextBox("", dt.ToString("dd.MM.yyyy"), new { #class = "form-control datecontrol", type = "text", data_val_date = "Field must have format dd.MM.yyyy" })
<i class="fa fa-calendar form-control-feedback lowerzindex"></i>
}
The jquery datepicker has following implementation:
$('.datecontrol').datepicker({
onClose: function () { $(this).valid(); },
minDate: "-1M",
dateFormat: "dd.mm.yy",
});
So even the datepicker knows how the format should look like.
The last component is the validation by jquery.validation:
$.validator.addMethod(
'date',
function (value, element, params) {
if (this.optional(element)) {
return true;
};
var result = false;
try {
$.datepicker.parseDate('dd.mm.yy', value);
result = true;
} catch (err) {
result = false;
}
return result;
},
''
);
I know that the date is passed to server in some culture neutral format, but I thought that when I decorated code on numerous places with the requested format, this will ensure that the conversion into that culture neutral format will be done right. Or am I missing something else ?
Thanks
Your problem lies in the fact that you have not set proper Culture for your application. Your request end-up executing under culture that has month-day-year order (probably under en-US) causing you a problem.
The easiest solution is to set set the culture that actually has day-month-year order and . as date separator in your web.config, for example:
<configuration>
<system.web>
<globalization uiCulture="de-DE" culture="de-DE" />
...
https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
The MVC uses current culture when parsing and binding posted data to your models/parameters.
It is advised to use same date separator across entire scope - html, client, javascript, server culture, ...

Milliseconds are being truncated by an ASP.NET MVC Hidden Input element

I have a View that renders a list of items, and each item contains a Date property.
<%:Html.HiddenFor(m => m.Items[j].Date)%>
A number of other properties are hidden or shown, and the user is able to enter comments against any item and save these comments to the database. It's a 'bulk edit' type View.
I've used these Views before to good effect, but I'm having a problem with the Date property because it renders thus
<input name="Items[3].Date" type="hidden" value="3/05/2012 11:56:48 AM" />
The problem is that I need to use the DateTime as a part of the primary key for this data item. I could truncate the milliseconds in the database to allow the match but there is no guarantee that there will only be one data point per second.
How do I ensure that the hidden input field for my DateTime retains all of the property's information, including the milliseconds component?
well do you really need to use
<%:Html.HiddenFor(m => m.Items[j].Date)%>
why not just keep it simple
<input type="hidden" name="Items[<%:j%>].Date" value="<%:model.Items[j].Date.ToString("dd/MM/yy/ HH:mm:ss.fffff")%>"/>
I've not had any success forcing the format of a DateTime in a HiddenFor field.
The DisplayFormat attribute can force the format for a DisplayFor field but has no effect on a HiddenFor field.
I resorted to the below no-quite-a-hack to get this to work - serialize and deserialize the ticks property to ensure the true time is retained.
public long DateTicks
{
get
{
return this.Date.HasValue ? this.Date.Value.Ticks : 0;
}
set
{
if (value == 0)
this.Date = null;
else
this.Date = new DateTime(value);
}
}
Use
<%:Html.HiddenFor(m => m.Items[j].Date.Ticks)%>
Use the DisplayFormat attribute on the Date property in your model, and spell out the milliseconds in the format string:
[DisplayFormat(DataFormatString = "{0:yyyyMMddhhmmssfff}")]

How to display Date in dd/MM/yyyy format in the View in Asp.net MVC3

Controller's Code
int No= Convert.ToInt32(reqCookies["NO"].ToString());
Student stud = db.Students.Single(n => n.No == No);
return View(stud);
Im passing the No after the user logs In and want the record of that logged In person to be displayed which i have successfully done.My issue is again with the Date.When the record of the Logged In user is displayed the Date of birth is displayed along with the time.Like this 2/19/2001 12:00:00 AM, instead i only want the date part and not time something like this 19/2/2001.
To achieve this i have tried to convert the date in dd/MM/yyyy format
DateTime DOB=stud.DOB.tostring("dd/MM/yyyy");
Getting Error:No Overload for method 'ToString()' takes 1 Argument
Code in my View is like this:
<td>#Html.DisplayFor(model => model.DOB.ToString())</td>
And when i try to change the format in the View
<td>#Html.DisplayFor(model => model.DOB.ToString("dd/MM/yyyy"))</td>
Getting Error:No Overload for method 'ToString()' takes 1 Argument
Where can i make the conversion and how to truncate the time Part from getting displayed.
You could use DisplayFormat in the model to format your date:
[DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}")]
public DateTime myDate { get; set; }
And then in the view:
<td>#Html.DisplayFor(model => model.DOB)</td>
Update:
Alternatively, since the DisplayFor() will simply output the date without any tags, you could just display the date without the use of templated helpers:
#Model.myDate.ToString("dd/MM/yyyy")
Or to display in a textbox you could use:
#Html.TextBox("Date", Model.myDate.ToString("dd/MM/yyyy"))

Resources