EXTJS Ext.util.Format.date Automatic date conversion - javascript

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.

Related

Angular 9 DatePipe: How to ignore timezone format

I am currently using angular 9 DateTime Pipe in order to format my dateTimes.
I am storing the dateTimes in database with DataTimeOffset.
When I am retrieving this dates from server are in this form: "2021-03-30T16:26:52.047+02:00"
I am using this code to apply the format to my dates:
const pipe = new DatePipe('en-Us);
const formatedDate = pipe.transform(date, 'dd.MMM.yyyy HH:mm:ss');
When I am doing this, the pipe is taking the browser time and format my date.
I know that this is the default option, if I am not sending the 3rd parameter to the transform function.
But I have a business need to show the dates as they are...but formatted in the format mentioned above,
My question is: How can I avoid the timeZone convert but still format the dateTime?
You may use var transformedDate = new Date(datepipe.transform(myDate, 'yyyy-MM-dd' + ' UTC'))
After many days of investigation, the only workaround was to use the library "Luxon".
https://moment.github.io/luxon/docs/manual/zones.html
With this library I can do something like this:
var keepOffset = DateTime.fromISO("2017-05-15T09:10:23-09:00", { setZone: true });
Which will keep the offset intact.

Set Date dynamically in extjs with value from backend

Back End is Java. front end is Extjs js.
When I set date in Java script as set value (new Date ), current date comes up in UI. when I set using back-end value date component is empty. Date comes up as string of numbers of length 13 in UI when debug. Date. parse is not working. how do i set value in UI from back-end. date from back-end is Java util date.
The 13 digit string of numbers you are talking about is Unix timestamp including milliseconds. You can convert the unix timestamp to whichever format you want at the frontend in ExtJS using format method of Ext.Date package.
let unix_time = 1527496785000;
let formatted_time = Ext.Date.format(new Date(unix_time), "Y-m-d H:i:s");
console.log(formatted_time) //2018-05-28 14:09:45

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

How to send AngularStrap datepicker value without timezone?

I'm wondering if it's possible to use AngularStrap's datepicker without it keeping the user's locale's timezone information. In our application we want to handle Contract objects that have an expiration date.
When adding or editing the contract object, there is a datepicker field for selecting the date. The following thing happens:
The user selects the date (e.g. 2013-10-24)
Angular binds the javascript date object to the ng-model field
The binded date object is in the user's timezone (e.g. GMT+3)
The user submits the form
The date gets sent to the server using Angular's $http service
In step 5 the date is converted to UTC format. The selected date was GMT+3 2013-10-24 at midnight, but the UTC conversion changes the date to 2013-10-23 at 9pm.
How could we prevent the conversion, or use UTC dates during the whole process? We don't want the contract's date to change based on the user's local timezone. Instead, we want the date to be always 2013-10-24, no matter what timezone.
Our current solution was to make small changes to the AngularStrap library so that the date won't change when sent to the server.
If we could get the user's selected timezone in the server, we could make another conversion there, but the server doesn't have that information.
All ideas are appreciated!
The issue isn't AngularStrap. Its just how javascript dates work and how JSON formats them for transmission. When you turn a javascript date object into a JSON string, it formats the string as UTC.
For example, I'm in Utah and it is now 07:41 on 2013-10-24. If I create a new javascript date and print it to the console it will say:
Thu Oct 24 2013 07:41:19 GMT-0600 (MDT)
If I stringify that same date (using JSON.stringify(date), I get:
"2013-10-24T13:41:47.656Z"
which you can see is not in my current timezone, but is in UTC. So the conversion is happening just before the form gets sent to the server when it gets converted from a javascript object to a JSON string.
The easiest way to do it would be to just change the date to a string of your own choosing prior to sending the date to the server. So instead of letting JSON change the date to UTC, (assuming you don't care about the time of day) you could just do something like this:
var dateStrToSend = $scope.date.getUTCFullYear() + '-' + ($scope.date.getUTCMonth() + 1) + '-' + $scope.date.getUTCDate();
That will give you a UTC-based string that looks like '2013-10-24' and then you can send that to the server, instead of the JSON format which includes the time info. Hopefully that helps.
UPDATE: As #Matt Johnson said, there are two ways to do it. You said: How could we prevent the conversion, or use UTC dates during the whole process?. If you want to use UTC, then use my above explanation. If you want to just "prevent the conversion", you could use the following:
var dateStrToSend = $scope.date.getFullYear() + '-' + ($scope.date.getMonth() + 1) + '-' + $scope.date.getDate();
A bit late but I spent my afternoon on this and someone might find it useful.
Another way to do this declaratively is to use the dateType, dateFormat and modelDateFormat attributes. Set these in either the config or the HTML e.g
angular.module('app').config(function ($datepickerProvider) {
angular.extend($datepickerProvider.defaults, {
dateFormat: 'dd-MMMM-yyyy',
modelDateFormat: "yyyy-MM-ddTHH:mm:ss",
dateType: "string"
});
});
DateFormat is the format the date will be displayed to the user in the date picker while modelDateFormat is the format it will be converted to before being bound to your model.
I also had default values coming from the server which I needed to be bound to the datepicker on page load. I therefore had to update the format the server serialized dates in JSON to match the modelDateFormat. I am using Web API so I used the below.
var jsonSettings = Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss";
The "Angular way" is to use the $filter service to format the date returned by the datepicker.
Example (HTML):
{{inpDate | date: 'dd-MM-yyyy'}}
Example (JS):
$scope.processDate = function(dt) {
return $filter('date')(dt, 'dd-MM-yyyy');
}
Plunker here

asp.net mvc datetime dynamic validation by clients date format

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

Categories

Resources