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

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.

Related

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

Momentjs return wrong date after minutes manipulation

In my php application I set the italian timezone like this way:
date_default_timezone_set('Europe/Rome');
the string above is located in my config.php file, the core of the app. Anyway, from the backend I using momentjs with CodeIgniter framework. When a user select a date from the properly input set this result:
Now I get the value from this input like this:
var end_date_temp = Date.parse($('#end-datetime').val());
And the initial result is wrong:
Tue Mar 01 2016 11:03:00 GMT+0100 (ora solare Europa occidentale)
The rest of code is:
var end_date = moment(end_date_temp).add(serviceDuration, 'minutes').format('DD/MM/YYYY HH:mm');
$('#end-datetime').val(end_date);
NB: I also tried to set moment.locale('it') but the same result appear, in my javascript libraries I've the italian timezone of momentjs. What is wrong?
UPDATE Code:
var end_date_temp = moment($('#end-datetime').val())._i;
var end_date = moment(moment(end_date_temp).add(serviceDuration, 'minutes')).format('DD/MM/YYYY HH:mm');
$('#end-datetime').val(end_date);
// parse the input string to a moment object, **specifying the input format**
var end_date = moment($('#end-datetime').val(), 'DD/MM/YYYY HH:mm');
// manipulate it as desired
end_date.add(serviceDuration, 'minutes');
// format it to the specified output format, and assign the result back to your field
$('#end-datetime').val(end_date.format('DD/MM/YYYY HH:mm'));
You can do this in one line of code if you like.
$('#end-datetime').val(moment($('#end-datetime').val(), 'DD/MM/YYYY HH:mm').add(serviceDuration, 'minutes').format('DD/MM/YYYY HH:mm'));
The locale setting isn't important with this particular bit of code, because you don't use any locale-specific functions or format specifiers
After a lot of attempts, I fixed in my timezone (italian) like so:
moment.locale('it');
var end_date_temp = moment($('#end-datetime').val()).format('DD/MM/YYYY HH:mm')
var end_date = moment(end_date_temp).add(30, 'minutes');
$('#end-datetime').val(moment(moment(end_date).toDate()).format('DD/MM/YYYY HH:mm'));
I declared the .locale as it, in the next time I formatted the time returned from the input text in my timezone as well. I've manipulated the date with the .add method, for do this I've create another instance of momentjs object. At the end I pass the value from the input, re-formatted the date again in my timezone format 'cause in the manipulation I lose the previous formatting. The final result is what I wanted. Hope this help, anyway, if someone find a solution more optimized than my I'll be happy to see.
momentjs is using the american date format (MM/DD/YYYY), enforce a format to get the right date:
var input = '03/01/2016 11:00';
var date = moment(input, 'DD/MM/YYYY HH:mm');
document.write(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js"></script>

Auto-populate field with date from another field + 14 days

Having searched endlessly for an answer, nothing has so far worked - so here I am hoping someone can assist.
I have 2 fields:
Action_Date & Deadline
The user updates the Action_Date field with the date they worked on the item. I then need to auto-populate the Deadline field with Action_Date + 14 days.
I have tried this so far:
function testCalc() {
var actionDate = new Date(document.getElementById("Action_Date").value);
var sla = 14;
var deadline = actionDate + sla;
document.getElementById("Deadline").value = deadline;
}
Action_Date calls this function via onblur()
The Deadline field auto-populates with the same date as Action_Date, in full format (e.g. Thu Jan 01 2015 00:00:00 GMT+0000(GMT Standard Time)14
Clearly the 14 days are not adding. Additionally I need Deadline to show the result in dd/mm/yy.
Any ideas most welcome!
Javascript dates are in milliseconds by default. So adding "14" to it is simply adding 14 milliseconds not 14 days. You will need to investigate more about Javascript Dates() here:
http://www.w3schools.com/jsref/jsref_obj_date.asp
Or use a framework of some kind like moments.js which is one of the best date handling frameworks out there. Date manipulation is one of the more complex things we developers have to do on the web due to issues with their local time, server time, etc.

DatePicker Error in Angular JS due to UTC

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.

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