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");
};
Related
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.
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
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/
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);