DatePicker Error in Angular JS due to UTC - javascript

I have selected the 12th of September 2014 in the UI.
Following is the code
ctrl.$formatters.push(function (modelValue) {
console.log(modelValue);
var dt = new Date(modelValue);
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
console.log(dt)
return dt;
});
The two console logs i see are the following.
09/11/2014
Wed Sep 10 2014 18:30:00 GMT+0530 (IST)
Am not sure why the conversion from UTC to local is not carried out correctly.
Thanks in advance.

Its not clear what you are trying to do. The input does not have a time. Do you want to add the current time of the day to the arbitrary date? Or do you just want a local representation of the date? I'm geussing the latter.
Instead of dt.setMinutes(...) and the following two lines, replace all three lines with:
return dt.toLocaleDateString();
If you ARE trying to set the time to now on whatever date is input (I don't know why...) but you might try:
dt.setTime( new Date().getTime() );
instead of the setMinutes(...) line.
then you can
return dt.toLocaleString;
All date objects are stored as miliseconds since, like 1972. It is best to use the built in Date object methods to get what you want from it. Here are the docs for reference.

Related

Avoid timezone correction for JavaScript Date

I have a JavaScript function that takes a number (1-31), creates a Date and sends it to a server via an AJAX request:
sendDate(d) {
let date = new Date(this.year, this.month, d);
htmx.ajax("GET", "/some/url", { values: { "date": date.toISOString() } });
}
The problem is, that JavaScript is doing some timezone correction which has the effect, that if I create a date like new Date(2022, 09, 14) I get a date Wed Sep 14 2022 00:00:00 GMT+0200 (Central European Summer Time) which when converted to ISO format becomes 2022-09-13T22:00:00.000Z, ie. the previous day.
I know I can use .toLocaleDateString(), but I would like to stick to the ISO-format and I would also like to avoid hacky solutions such as always creating the date with some specified time at the middle of the day or whatever.
Is there a simple way to create a regular date object and pass it on to a server without timezone shenanigans?
Values passed to the Date constructor are treated as local, toISOString uses UTC. Unfortunately ECMAScript doesn't have a timezone–free, date–only form.
If you want to use toISOString to format the timestamp, then one solution is to parse the values as UTC initially, e.g.
sendDate(d) {
let date = new Date(Date.UTC(this.year, this.month, d));
htmx.ajax("GET", "/some/url", { values: { "date": date.toISOString() } });
}
Example:
let d = new Date()
let year = d.getFullYear();
let month = d.getMonth()
let day = d.getDate();
let date = new Date(Date.UTC(year, month, day))
// Always shows the current local date as 00:00:00Z
console.log( date.toISOString() );
You should also trim the Z from the end since the timestamp really is local.
There’s a way to do that: store the date as the UNIX timestamp. I do it this way and when it’s needed, I pass the timestamp from server to client and convert it into local date.
That said, I don’t think it’s a good idea to build the date on client and pass it to the server, since it could be modified on client. I believe it’s mostly done this way (and that’s also how it’s done in my projects): on the server side, you check the current timestamp (at the time request is sent) and do with it whatever you want.
It appears that you allow your user to pick a date. It would be a good approach to convert it then to timestamp and pass it to the server.
How would you do that? If I return date.getTime() and then parse it (in python) with datetime.fromtimestamp(int(request.GET['date']) / 1000) I still get the same timezone issue...
You won't have any issues in this case - apart from the fact your server just could happen to have a different local time. A time-zone independent solution would have to use utcfromtimestamp instead of fromtimestamp.
Either way, the timestamp itself can't have any timezone problems by definition.
See RobG's Answer... using the new Date(Date.UTC(year, month, day)) formatting is much better.

angular $http.post changing date to UTC date

I was trying to post some data to my REST api which has date.
Now while I debug, my date parameter is a JS Date object with correct date in my timezone: Tue Apr 04 2017 00:00:00 GMT+0530
after it leaves my code, and I see the same in network tab, it is converted to UTC date: "2017-04-03T18:30:00.000Z"
I searched for the solution according to which I need to include locale file of angular in my index.html which I did:
<script type="text/javascript" src="resources/js/angular/angular-locale_en-in.js"></script>
but it doesn't help.
I've seen solutions like adding date format to filter or something, but I want a global solution.
Any help?
Thanks :)
Handling date, time, and timezone have confused me too. May be this answer gives you some insight on how you can handle them.
Try the following code in Chrome's developer console and see how same date is presented in different formats:
var date = new Date();
date.toISOString(); // "2017-04-29T09:54:28.714Z"
date.toGMTString(); //"Sat, 29 Apr 2017 09:54:28 GMT"
date.toLocalString(); //"4/29/2017, 3:24:28 PM"
Any date that you create on client always records the date at zero timezone offset i.e. UTC+/-00:00 Z. For simplicity you may think UTC and GMT as same. When it comes to display purpose the same date is presented as per the browser's timezone. If you do console.log (date) it'll output Sat Apr 29 2017 15:24:28 GMT+0530 (IST) but that doesn't mean that the internal recording of the date is as per browser's timezone. It's just presented on screen/console as per browser's timezone.
Look at date representations not as being converted from one timezone to another but look at them as different representation of the same date. In your browser it is represented as GMT+0530 offset and when it is sent to server it is the same date at zero timezone offset.
As per your comment, if you choose 4th Apr at 00:00 AM in GMT+0530 timezone, internally it'll be 3rd Apr at 18:30 PM in at GMT+0 i.e. zero timezone offset. Let it go to server as it is. When you need to use this date, it comes back from server as 3rd Apr and it'll be displayed in browser as per the browser's timezone offset. There is no conversion involved, it is one date with different representation.
I once asked a related question, may be this adds more clarification.
And overall, this answer is still same as #geminiousgoel and #charlietfl answers.
Scenario :
Send date from UI into API call as an epoch time (UNIX Time) instead of date string. You can use getTime() method to convert the date into epoch time.
var dateStr = "Tue Apr 04 2017 00:00:00 GMT+0530";
var dateEpoch = new Date(dateStr).getTime();
console.log(dateEpoch); // 1491244200000 (Local Time)
At receiver end, they have to convert this epoch time (UNIX time) into Date again.It will give the same local date\time that pass from the UI.
Sample screenshot
Like charlietfl suggested, probably the global hack would be to override Date.prototype.toJSON() method, but that's not a good practice.
Where are you using your $http.post call? The best place to submit an $http request would be in a service. If you use a service, then I suggest you to enwrap your public service API, so that you could have "public" and "private" methods: these could be utilities to perform common operations, such as data transformations, validations..
angular.service('bookStoreService', ['$http'], function($http) {
var normalizeBooks = function(booksArray){
booksArray.forEach(function(book){
// do something on the book
});
};
var updateBooks = function(books){
normalizeBooks(books);
$http.post('myurl', books);
};
return {
updateBooks : updateBooks
};
});
Passing UTC date to server is desired behavior. The client APIs are supposed to handle UTC time instead of assuming the dates are all local dates.
But anyways, you can convert the date to string based on local time zone, and pass the string to server.
i think you just can pass it as string (if the api you use accept strings) with the format you need, let say "Tue Apr 04 2017 00:00:00 GMT+0530" and save it in back-end as string and then when you retrieve it, it will be string and so it will not be changed in any way.
Jindal saab, It will work like this. When we select any date with date picker or just pass any value it takes the original local date but when we pass that value further it converts it into UTC, thereafter it needs to convert to local zone again at receiving end. Database saves date-time in UTC format.
Did you added the angular-locale_en-in.js library to your app? Something like this....
angular.module('myAngularApp', [
'ngLocale'])
Otherwise, the js library won't have any effect in your angular application.
Append UTC at the end so that Browser converts it into UTC date
var dateToServer =new Date(dateFromUser+" UTC");
now the dateToServer will be UTC DateTime format.
Json serializer parse date from string. On a client the date properties are stored as local date in browser time zone. When you are posting your object to server all date properties converts to utc string. In most cases it is a properly behavor. But sometimes you need set and send date in a server time zone. Often it is need when you should set only date whitout time. In that case you should define string propertie and set it manualy. I usaly apply this trick.
class Obj{
d: Date
}
class ObjDto{
constructor(obj: Obj){
this.d= dateTimeToIsoLocalDateString(obj.d)
}
d: string
}
...
export function DateTimeToDate(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
export function dateTimeToIsoLocalDateString(dateTime: Date): string {
if (dateTime === null) {
return null;
}
let date = DateTimeToDate(dateTime);
let res = date.toISOString().replace("Z", "");
return res;
}
For more understanding this theme you may learn this topic
//in res data of rest service in x the value is date in y value of y-axis
for (const i in res) {
console.log(i);
const a = {x: new Date(this.mimikatzlog[i].x), y: this.mimikatzlog[i].y};
this.policies.push(a);

Convert Date Value to Timestamp - Post Request - Ember.js

My handlebars code is as followed.
{{bootstrap-datepicker value=from placeholder="MM/DD/YYYY"}}
Here the user picks a date from a calendar to get the from date. This is for a form.
My problem is the format is as followed: Sun May 29 2016 00:00:00 GMT-0700 (PDT)
and the post request requires milliseconds since epoch format.
SO
all the code sample I've seen to fix these problems, require the date in the function.
example:
var myDate="26-02-2012";
myDate=myDate.split("-");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
alert(new Date(newDate).getTime());
or
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
or
var fromFormat = moment('from').fromFormat(moment(), 'milliseconds');
but I only have the name value as it changes all the time.
I've got moment-js, date-picker and a couple other add-ons. Any resources or code snippets will be appreciated.
So I finally figured it out with some help from friends.
I created an action that took the formatted date from date-picker and transformed it into UNIX time in milliseconds.
actions: {
PublishForm{
var fromDate = moment(from).valueOf();
}
}
**I've changed it this way due to issues displaying the date with the bootstrap-datepicker when you use the changeDate.

How can I set up a correct format while doing new Date() in jQuery?

I have a date in a following format:
12/11/2015 07:12 PM
In jQuery I'm doing:
var parsedDate2 = new Date(date);
alert(parsedDate2);
And that prints me:
Fri Dec 11 2015 07:12:00 GMT+0100 (Central European Standard Time)
and that almost works correctly, mostly because in my example (12/11/2015 07:12 PM) the format is DD/MM and not MM/DD. However, jQuery treats it as the month is first. That's a problem, because when I chose as input:
19/11/2015 07:17 PM <--- (19th of November)
I'm getting:
Invalid date
So how can I set up the correct format here with the day before the month?
Ugly, but it work, with JS only :
a = "12/11/2015 07:12 PM";
b = a.split(' ');
c = b[0].split('/');
bad = new Date(a);
alert('bad : '+bad);
good = new Date(c[1]+'/'+c[0]+'/'+c[2]+' '+b[1]+' '+b[2]);
alert('good : '+good);
The other way is to use Moment.js parsing tool
Think that you should use more specialized and focused library along with JQuery, for me the best one is Moment.js - it has all and more than needed to date-time parsing and formatting and doesn't do something else.
Also, there are some other alternatives, like date.js and globalize.js
It's in the form of mm/dd/yyyy. Try 11/19/2015 07:17 PM. Sadly, jQuery doesn't know which format you're using and so, uses the deafult one.
Unfortunately, the Javascript Date system isn't very malleable when it comes to adding date formats. Here is a reference from Mozilla. I think wierdpanda has the right idea, write a function that accepts your date format, reformats it before feeding it to new Date(), and returns the result. Use this in place of where you have new Date(), and all should be good.

Angularjs, Datepicker one day beind

I understand that the datepicker (I'm using AngularStrap's datepicker) is "behind" a day because of how dates are calculated in javascript. My problem is, how to I get it to not take the timezone into consideration and just stick with the entered date... no adjustments?
I select February 1, 2014 in the datepicker. My value on the screen is 2/1/2014 and I want that value to be saved. However, the datepicker turns this into Fri Jan 31 2014 19:00:00 GMT-0500 (EST) apparently because it subtracts the 5 hours for my timezone from the entered date. I do not want this. If I enter 2/1/2014 I want that date, regardless of the timezone.
What is the best way to intercept/change/edit this value so that entering 2/1/2014 gives me exactly that date... no conversion for timezone? Should I modify the datepicker code itself (this seems like a bad idea)? Should I change the value myself prior to sending it to the backend by adding in some sort of offset? If so, how do you add time to a value that console displays as Fri Jan 31 2014 19:00:00 GMT-0500 (EST)?
I solved this problem with a custom directive https://gist.github.com/weberste/354a3f0a9ea58e0ea0de
It's for Angular Bootstrap datepicker but I guess it should work for AngularStrap datepicker as well since it only depends on the corresponding ngModel rather than the datepicker itself.
Essentially, I'm reformatting the value whenever a date is selected on the datepicker (this value, a yyyy-mm-dd formatted string, will be stored on the model) and whenever the model is accessed to populate the view, I need to wrap it in a Date object again so datepicker handles it properly.
In other words, it is exactly doing the interceptions that you ask for in your question.
I know this thread is kind of old but since there is no accepted solution I thought I'd offer what finally worked for me after lots of messing around:
The issue in my case was that the datepicker was using the wrong timezone so when I would try to edit an event, the wrong date would display even though the correct date was stored in the db. The following fixed it for me:
var evDate = new Date(data.eventDate); //data.eventDate is the date string
evDate.setMinutes(evDate.getMinutes() + evDate.getTimezoneOffset());
$scope.eventInfo.eventDate = evDate;
I found this solution here: https://github.com/angular-ui/bootstrap/issues/2628
If you don't mind loading another resource, then I would recommend using MomentJS as it takes the pain out of dates in JavaScript. You can do something like `moment(datepicker value).local()' to get the date without the timezone offset.
http://momentjs.com/docs/#/manipulating/local/
I have found a way. convert that date to string first. here is the code.
var SelectDate = $scope.GetFormattedDate(Date.parse($("#Date").datepicker("getDate")));
$scope.GetFormattedDate = function (CalDate) {
var re = /-?\d+/;
var WDate = CalDate.toString();
var m = re.exec(WDate);
var lastDate = new Date(parseInt(m[0]));
var mm = lastDate.getMonth() + 1;
var dd = lastDate.getDate();
var yyyy = lastDate.getFullYear();
var formattedDate = mm + '/' + dd + '/' + yyyy;
return formattedDate;
}
Now Pass SelectDate to your controller. bingo problem has been resolved :)
Guys if you are experiencing this problem is because probably,you are reactivily ,puting data in boostrap datepicker.This solution worked for me.
First you check if date is null
dateBegin===null?dateBegin=null:dateBegin = new Date(formatDate(dateBegin,'yyyy-MM-dd','en'));
**if is null you set its value to null which you are going putt in your Form Group and in Form Group Control
this.ugovorForm = new FormGroup({'dateBegin':new FormControl(dateBegin)})
else you will set Date and format it using formatDate property , provided by Angular.I was struguling with this problem for along time.And its because I'm loading dates from Database.Good Luck;

Categories