Consider the following dummy code in a JavaScript file in an ASP.Net MVC5 Project.
var $grid = $("#grid")
var postData = $grid.jqGrid("getGridParam", "postData");
postData["xyzId"] = $("#xyzId").val();
postData["date"] = $("#date").val();
$grid.setGridParam({ postData: postData });
$grid.setGridParam({ datatype: "json", page: 1 }).trigger("reloadGrid");
Following is the Controller's ActionMethod where the request arrives...
public ActionResult GetXyz(int xyzId, DateTime? date)
Keeping the date nullable is the need because it is an optional selection.
PROBLEM:
The date format in Culture settings of .Net Framework is "DD/MM/YYYY" and when we send "02/10/2016" it accepts as "February 10, 2016" (which is wrong btw) but when we send "16/10/2016" it reads it as null. This is only happening when we are passing dates in jqGrid Reload operation. Whereas, in normal ajax call, everythins is working well
e.g. "02/10/2016" => "October 02, 2016",
and "16/10/2016" => "October 16, 2016".
Can anyone help?
It's recommended to use only locale independent formats to transfer the data. It's common rule for numbers, date, ... You can convert $("#date").val() to the format YYYY-MM-DD (ISO 8601 format of date) before assigning to postData.xyzId? I think that ISO date format is default for Newtonsoft.Json used in MVC.
Typically one use formatter: "date" with optional formatoptions with newformat property. In the way you hold internally and transfer only locale independent data, but the user will see local specific dates (based on formatoptions.newformat which you specify explicitly in colModel or the implicit value inherited from grid.locale-XX.js).
Catch the date as string
public ActionResult GetXyz(int xyzId, string date="")
and then format it in conventional way:
var Date= DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Hope this will help :)
Related
Our previous developer create a generic method that retrieve all user input that has an update/changes.
it looks like this (user side/JavaScript/Kendo):
param._updated = JSON.stringify(rows._updated);
I am somehow desperate that when that *rows._updated contains a Date Value uncle JSON convert it into other String format that result to DateTime Difference for example:
dateField = 11/1/2015 // <--Original User Input
rows._updated = { dateField: November 1, 2015 0:00:00 GMT+080 ... }
param._updated = { "dateField": "2015-10-31T16:00:00.0000Z"... }
which would now result to a conflict.
since the above code was generic field that might contain different data and type, I am trying to solve this issues at the server side but i failed to achieve the original date value.
NOTE: our users has 2-5 different timezone so it's kinda hard to hard code the conversion.
related issues: here
It's getting late. Thanks in advance!.
I somehow achieve what I want to by the following approach
1.) At backend Convert the DateTime to UTC Format
string dateUTC = paramDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
2.) Now I have created a method that will handle the convertion of UTC Date to PlainDate
public static string UTCtoPlainDate(string dateUTC)
{
if (string.IsNullOrEmpty(dateUTC)) return "";
DateTime dateTime;
// Assume date in UTC format, e.g. '2015-03-31T12:00:00.000Z'
DateTime.TryParseExact(dateUTC, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out dateTime);
return dateTime.ToString("yyyy-MM-dd") ?? "";
}
I have a date field which contains data coming in from the database as 2015/07/31 13:01:53.180z.
Datetime is stored in UTC on database.
My code looks like this:
var startDateTime = Ext.util.Format.date(StartDateTime, 'm/d/y g:i:s A');
But the output I get is the conversion of UTC to IST(Indian).I checked on Chrome,Mozilla and IE.
I got same output all the time
Does ExtJs does this? Because I haven't wrriten any method for conversion.
I use ExtJs 4.1.1
I would appreciate any help on this.
Timezone is appended in the string->JS Date conversion.
To parse the date from database without timezone conversion you should use the Ext.Date.parse explicitly, not automatically through model field type 'date' or simply JS constructor new Date().
For example:
var db_date = '2015/07/31 13:01:53.180z',
js_date = Ext.Date.parse(db_date.substring(0,db_date.length-5), 'Y/m/d H:i:s'),
date_to_show = Ext.util.Format.date(js_date, 'm/d/y g:i:s A');
Obviously "substring" must be replaced by something better, for example you could format db date (cutting timezone part) in the web service serialization.
If you achieve to clean the date string in the web service you can also add "dateFormat" attribute to model fields to parse date correctly into models.
I send from JS (with JSON) to server (C#) a string date in format "dd/mm/yyyy" - for example "23/10/2014", but C# DateTime gets null. If I send "10/23/2014" it works.
I use MVC4.
How can I change that format that DateTime gets to I'll be able to send "23/10/2014"?
Not a direct answer to your question but I think you're safer to send the date as: yyyy/mm/dd
Then you don't need to worry about internationalisation. MVC will parse this correctly.
EDIT
Matt made a good comment below. The format of the date should be: yyyy-mm-dd which is in agreement with the ISO 8601 standard.
you can specify the date format in the serialization settings
var jsonString = #"{'ID':'1','Date':'23/10/2014'}";
JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
DateFormatString = "dd/MM/yyyy"
};
var result = JsonConvert.DeserializeObject<TheType>(jsonString, jSettings);
I have a Custom Attribute for DateTime validation with given dateformat and also javascript validator which are provide me both client side and server side validation. But now I should change my datetime validation so that it would be performed according clients local DateTime format and I do not know how.
I couldn't find anything that help me.
So please advise me how can I implement at least client side DateTime validation or how can I get client's date format by javascript.
If you can determine the locale of your user, you can use .Net globalization classes to assist with server-side parsing of date time strings. For example:
// Parsed as January 4th
var dt1 = DateTime.Parse("1/4/2013", new CultureInfo("en-US"));
// Parsed as April 1st
var dt2 = DateTime.Parse("1/4/2013", new CultureInfo("en-GB"));
But the best thing to do is avoid this entirely. In your JavaScript code, get the value back as an ISO8601 string - which is culture invariant. Native browser support for this varies. The built-in functions work in IE9+.
// This returns an ISO formatted date, in UTC.
var s = yourDate.ToISOString();
One way to get full browser support, and get an ISO date without converting to UTC, is to use the moment.js library, where ISO8601 is the default format:
// This returns an ISO formatted date, with the user's local offset.
var s = moment(yourDate).format();
// This returns an ISO formatted date, in UTC.
var s = moment(yourDate).utc().format();
When you send these values to the server, you can parse them in your .Net code without concern for culture. The format is already culture invariant. To prevent the server's time zone from interfering, you should parse them as a DateTimeOffset:
// assuming this is an ISO value you got from the client:
var s = "2013-04-20T09:00:00-07:00";
// simply parse it
var dto = DateTimeOffset.Parse(s);
// if you don't care about the offset at this point:
var dt = dto.DateTime;
Of course, if you want to fail gracefully, you can do this instead:
DateTimeOffset dto;
var isValid = DateTimeOffset.TryParse(s, out dto);
I need to pass javascript date value to vb.net function.
Method iam using now:
convert javascript date to string
store it in hiddenfield
retrieve string from hidden field in server code and parse it using date.parse
the trouble is that the Javascript dateformats
toString() - Sat Apr 4 22:19:00 UTC+0530 2009
toDateString() - Sat Apr 4 2009
toLocaleString() - Saturday, April 04, 2009 10:19:00 PM
doesnt match vb date format. I am getting error that its unparseable.
Thanks in advance for the help
The problem with using ToLocaleString is that you lose timezone info and its obviously locale specific which means you need to parse it with the right culture.
I was thinking:-
DateTime d = DateTime.ParseExact(sInput, "ddd MMM d HH:mm:ss UTCzzzz yyyy" , CultureInfo.InvariantCulture);
But that isn't cross browser compliant (the ECMA spec does not define what toString should actually do).
However we do know that the value of a Javascript Date object is the number of milliseconds from midnight Jan 1, 1970. Hence you could instead store the .valueOf of a date object in your hidden field. Use Int32.Parse on the string first, create a TimeSpan from the that value and add it to a DateTime of Jan 1, 1970 00:00:00 UTC+0000.
int milliseconds = Int32.Parse(inputString);
TimeSpan t = TimeSpan.FromMilliseconds(milliseconds);
DateTime base = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result = base + t;
Why not instead pass the Javascript date as a string and then convert it to a date type in VB.net.
Public Function ConvertJavaScriptDate(ByVal d as String) As Date
Return Date.Parse(d)
End Function
Another option is to use CType(d,Date). CType is a lexical cast that will try a variety of ways to convert the string value to a Date.
I'm not terribly familiar with the difference between a JavaScript Date and a VB.Net Date in terms of format, but if you post an example I'm sure we can get a basic conversion going.
Since I don't have to worry about culture difference I am going to use toLocaleString().
toLocaleString() parses fine to a string compatible with Date.Parse().
Anyway thanks for posting your replies.
This just a datetime formating issue can you look this post for more details.
How we can resolve the datetime problem shifting the Access DB from production server to live
You can also use DateTime.ParseExact() to tell the VB code exactly what the incoming string should look like.