asp.net mvc datetime dynamic validation by clients date format - javascript

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);

Related

Convert all date/datetime elements to local timezone

how to convert all elements with date/datetime string to display in users local timezone in javascript(jquery, moment or anything). all datetime text with classname to localtime zone using jquery or moment.js or any javascript methods.
In https://momentjs.com/timezone/ there is a timezone method. but how can we do it in one method
What I would do is make sure that the server returns datetime in ISO 8601-format per here:
Then you can use that datetime or get all elements with appropriate class associated with it using javascript or jquery.
Javascript for converting UTC DateTime to local user's DateTime
var utcDateTime = '2019-05-15T08:33:48.000Z'; // ISO-8601 formatted date returned from server
var localDateTime = new Date(utcDateTime);
The localDateTime will be in the right local time which in my case would be three hours later (GR time).
jQuery to change val of said elements
$('.yourDateclass').each(function() {
$(this).val(localDateTime);
});

Convert client date / time string to JSON date / time string using JavaScript

I am trying to convert a client date / time string on a form into a JSON date / time string using JavaScript and moment (for a Django REST API back end). Here is what I have so far:
document.getElementById("dt_tm").value =
moment(document.getElementById("inp-st").value, "DD/MM/YYYY HH:mm").toJSON();
Two problems with this:
The date format cannot be hard coded as the client may have a different date format,
moment adjusts the date / time and I don't need it to do that because the back end performs that function (using Django time zones).
So for example:
moment("14/05/2016 18:00", "DD/MM/YYYY HH:mm").toJSON() =
"2016-05-14T17:00:00.000Z"
When what I need is:
"2016-05-14T18:00"
(In this example my time zone is currently GMT+1.)
If you would like toJSON to return the date in a different format, redefine moment.fn.toJSON to that it returns with your custom format instead of the default ISO8601 date format. This is outlined in the documentation.
moment.fn.toJSON = function() {
return this.format("YYYY-MM-DDTHH:mmZ");
};

Handling Datetime datatype between javascript and WebApi 2

I would like to know whether the following is the right method to handle datetime data type in WebApi 2, Javascript and database.
DateTime from Javascript to WebApi:
var date = new Date();
var datestring = date.toISOString();
//Send datestring to WebApi
DateTime from WebApi to Javascript:
//on getting datetime value from `http.get` call
var dateFromServer = new Date(dateFromServer);
WebApi:
Incoming date
do nothing simply store the datestring returned in database column with datatype datetime
Getting date from database and Returning date to client:
no datetime manipulation (simply return as per WebApi Json serializer ex: 2015-10-23T18:30:00). Client would automatically convert the UTC datetime to local datetime
Yes if you don't want to handle any information about user Timezone etc... this is an acceptable way.
Just make sure that any time you want a date produced from the server for a comparison or something else to use the c# DateTime.UtcNow
method.
I think Having a "Global UTC Convention" its a quite safe and good solution but it has some limits.
For example if you want to Alert all of your users located in different timezones at 09:00 am (on each user's country) then its impossible to know when its "09:00" for each one.
One way to solve this(and it's the one i prefer), is to store manually each user's timezone info separately on the database, and every time you want to make a comparison simply convert the time.
TimeZoneInfo.ConvertTimeFromUtc(time, this.userTimezone);
Alternatively if you want to store all timezone information on the server you can :
Send your date from javascript to the server using the following format :
"2014-02-01T09:28:56.321-10:00" ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset.
Declare your WEB API 2 Date types with the "DateTimeOffset" type.
Finally store your dates within the database using the "datetimeoffset" type.
This way any time on the server or the database you have all the information about the user's time and timezone.
You will find this article useful

EXTJS Ext.util.Format.date Automatic date conversion

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.

.NET WebService JSON date in ISO-8601 format

I am calling a .net asmx webservice that returns a number of fields. One of the fields in a date. The date is in the format of: "effective_date":"\/Date(978411600000)\/"
According to this SO question: How do I format a Microsoft JSON date? it would be better if the date returned was in ISO 8601 format, this way JavaScript would be able to interpret it as a date.
Currently I use the following javascript: new Date(d.effective_date) and I get the message Invalid Date. According to the linked SO question I should be able to do this if I can get the web service to pass the date in ISO format rather than in \/Date(978411600000)\/ format.
My question is, how do I get the webservice to return the date in ISO 8601 format?
Note:
I'm aware that I can use this (per the answer from the linked question): var date = new Date(parseInt(d.effective_date.substr(6)));, however it is mentioned in a comment that Incoming date values should be formatted in ISO-8601, so I'm wondering how to get the incoming date from the web service to be in this ISO format.
You may use:
var date = new Date(d.effective_date);
date.toISOString(); // ISO-8601 formatted string
JSFiddle: http://jsfiddle.net/nanndoj/gjtkvrsy/

Categories

Resources