I use Datadatables in server-side mode.
For the date my server return a JSON DATE mode for example:
"2015-12-18T17:04:27Z"
How can I format the DataTables localization automatically format of the language of the browser?
Thank you
Assuming this "2015-12-18T17:04:27Z" is the value returned from the server, here is my take on it.
new Date("2015-12-18T17:04:27Z").toLocaleDateString() // =>"12/18/2015"
new Date("2015-12-18T17:04:27Z").toLocaleString() // => "12/18/2015, 12:04:27 PM"
There are a number of methods you could use to format it how you like here.
Note: The comments are the outputs determined by my Locale, yours may differ
Related
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
I have a Build model with a start_time field, which is of type models.DateTimeField. On the other hand I have a BuildSerializer class that includes this start_time field. Now when I print the timestamp in my templates, I get a result like this:
{{ build.start_time|format:'DATETIME_FORMAT' }}
in my template will become:
April 24, 2015, 8:03 a.m.
However, the serializer outputs a different value:
2015-04-24T08:03:39.336922Z
This is fine as it is a standard JSON date representation. However, I’d like to display it in regard to the user’s locale, like Django does when I use the above template snippet does.
I tried to use
timestamp = serializers.DateTimeField(format=settings.DATETIME_FORMAT)
but DRF uses a different way to format date outputs, so this will just output:
"N j, Y, P"
for the default en-us locale.
Is there a way to format a date exactly like Django does? I’m interested in both a python or a JavaScript solution, as I process the JSON in a JS function (AJAX callback) anyway.
I would highly recommend keeping your dates formatted as ISO 8601 (that's what the default is) as it is a consistent and standardized date format, so you don't need to worry too much about parsing dates manually anywhere. Most languages can parse ISO 8601 dates, and those that can't by default generally have libraries which can do it for you.
Is there a way to format a date exactly like Django does?
Django REST framework by default only supports formatting a date-related field using a single formatter, which is ISO 8601 by default. This is for general consistency, so clients can send an OPTIONS request and parse the date format directly from there and rely on the date format never changing.
You can override this behaviour by either having a property on your model or a SerializerMethodField that overrides the return value such that it calls Django's date formatting utilities if you want to localize the value on the backend. Alternatively, you can override the default DateTimeField's to_native method and do the formatting there, that way you can have a field that can be used across serializers so the localization is consistent.
I’m interested in both a python or a JavaScript solution, as I process the JSON in a JS function (AJAX callback) anyway.
The JavaScript solution that we use for parsing ISO 8601 times is Moment.js. While some browsers can parse ISO 8601 times, not all can and it is easier to pass them off to Moment so they can be converted in JavaScript Date objects.
// parse the incoming date/time string
var start = moment(response.start_time, moment.ISO_8601);
The first argument to moment is the string to be parsed, and the second argument is the format to parse from. moment.ISO_8601 is a special hook that can automatically parse it as a valid ISO 8601 time, which is why we use it.
From there you can use the browser's Date localization to present the user a localized version of the time. Date objects provide toLocaleString(), toLocaleDateString() and toLocaleTimeString() methods that can be used to format the different parts of the date (or the entire thing) how the user is expecting it.
Testing locally on Chrome (on Ubuntu, en-US) I get the following outputs for the methods
> (new Date()).toLocaleString()
< "6/2/2015, 7:23:03 PM"
> (new Date()).toLocaleDateString()
< "6/2/2015"
> (new Date()).toLocaleTimeString()
< "7:23:12 PM"
Which is how I've configured my date settings for this browser. This has the additional bonus of always using the current time zone for the system, so you don't need to worry about that part of localization - it's handled automatically.
I have came to a solution pretty fast, although I consider it a bit ugly:
from django.utils import formats
class BuildSerializer(serializers.ModelSerializer):
timestamp_django = serializers.SerializerMethodField()
def get_timestamp_django(self, obj):
return formats.date_format(obj.timestamp, 'DATETIME_FORMAT')
class Meta:
model = Build
fields = ('timestamp', 'timestamp_django', …)
This way I get the best of both worlds, as I can still use the JSON date for other purposes (like filtering or sorting).
Here is my solution, based on Kevin Brown's answer:
from django.utils import formats
from rest_framework import serializers
from rest_framework.settings import api_settings
class DateTimeField(serializers.DateTimeField):
"""DateTime field whichs supports Django's format definitions."""
def to_representation(self, obj):
if api_settings.DATETIME_FORMAT in formats.FORMAT_SETTINGS:
return formats.date_format(obj, api_settings.DATETIME_FORMAT)
return super().to_representation(obj)
class DateField(serializers.DateField):
"""Date field whichs supports Django's format definitions."""
def to_representation(self, obj):
if api_settings.DATE_FORMAT in formats.FORMAT_SETTINGS:
return formats.date_format(obj, api_settings.DATE_FORMAT)
return super().to_representation(obj)
class TimeField(serializers.TimeField):
"""Time field whichs supports Django's format definitions."""
def to_representation(self, obj):
if api_settings.TIME_FORMAT in formats.FORMAT_SETTINGS:
return formats.date_format(obj, api_settings.TIME_FORMAT)
return super().to_representation(obj)
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
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 made this code for inserting data to an system mail that know to work with xml file.
the problem is that i try to create some javascript code for getting the current date of day, and then put it inside the filed date, but without success.
i know hot create the date in javascript, my problem is in thx xml file, i mean
how can i impplemt the date inside the filed date in the xml file.
the code(xml side):
123456
NOW
COMPLETE
ENGLISH
1274
liran
**
413
3280
86308
;
UNIX
email;dateofday
liroy7#gmail.com;(i want here to return the date from the javascript)
thanks,
I'm not sure I understand, but you can use getTime() on your Date objec to insert it into the XML file as milliseconds, and if you need to convert it back into a JavaScript object you can parse it directly.
function putInXmlFile(d) {
writeToXML(d.getTime());
}
function getFromXmlFile() {
var date = new Date(getFromXML());
}
It works because the JavaScript Date object can parse from the milliseconds from the epoch (which is returned by getTime).