I am trying to sync my client app time to my server time (it matters because the app is serverless and has offline-work). On the app startup I calculate the time difference and then override the Date.now() method to add the difference into original now. For example assume this code:
Date.__serverDifference = calculateServerDifference();
Date.__now = Date.now;
Date.now = () => Date.__now() + Date.__serverDifference;
and it works fine. But the problem is about other Date functionalities. For example if I use new Date() it will return original time and it doesn't care the overridden now method.
As the MDN documentation says:
JavaScript Date objects represent a single moment in time in a
platform-independent format. Date objects contain a Number that
represents milliseconds since 1 January 1970 UTC.
Is there any way to override the js Date Class to return all current times according to this new calculation?
The best approach would be to create helper methods that include the offset for all functions for which the built-in functions don't return the desired value. Your Date.__now is a start, but you could also have:
const offset = calculateServerDifference();
const newDateIncludingOffset = (...args) => {
const date = new Date(...args);
date.setMilliseconds(date.getMilliseconds() + offset);
return date;
};
And then replace all instances of new Date(...args) with newDateIncludingOffset(...args). If you have a lot of references to new Date already - bite the bullet and change them appropriately.
While you could change methods on the prototype, that's not such a good idea - using your own functions and methods while not changing the built-ins is a much better approach.
You could also replace window.Date entirely with something new, with your own methods, allowing you to change the Date constructor to factor in the offset you need - but again, that's not a great idea and can lead to fragile code and incompatibility issues.
Related
I have the following code:
function localDateHandler(momentObj) {
let start = momentObj.clone();
let update = start.add(10, 'days');
console.log(update); // Does not change, SHOULD be ten days more than momentObj
console.log(momentObj);
}
I am using the following React component to change the date:
<DateTimePicker value={eventDate} onChange={localDateHandler}/>
The info for the component is here: https://material-ui-pickers.dev/
When I change the date the date is not incremented by the number of days listed in the first block of code (I explain more in the comments)
Thank you!
I reproduce and this works with not any problem. What you have seen maybe caused by one of these case:
You might have briefly looked at _i of moment object, this might be the initial object (which could derive from momentObj.clone()), instead, you should look _d instead (moment object internal properties doc)
The most commonly viewed internal property is the _d property that holds the JavaScript Date that Moment wrappers.
You might not have use the right version of peer dependency for moment adapter (installation guide)
Important: For material-ui-pickers v3 use v1.x version of #date-io adapters.
Codesandbox for demonstration, you should open the log to check
JS code works as it should (the comment is clearly false):
function localDateHandler(momentObj) {
let start = momentObj.clone();
let update = start.add(10, 'days');
console.log(update); // Does not change, SHOULD be ten days more than momentObj
console.log(momentObj);
}
localDateHandler(moment());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Yields in my case:
"2020-08-24T22:29:35.347Z"
"2020-08-14T22:29:35.347Z"
I'm guessing something wrong with rendering? Then I suspect you'd have to modify eventDate somewhere in localDateHandler, not some local variable not bound to the widget.
I was wondering why the Kotlin JavaScript Date class returns a Double for the getTime function. According to the documentation, the getTime function should return the number of milliseconds since 1 January 1970 00:00:00 UTC.
I know that JS doesn't have a 64 bit numeric representation, but since Kotlin emulates Longs I feel like the value returned by Date.now() and Date().getTime() should be a Long. At the very least it would make more sense to return an Int.
Is there any reason that it returns a Double instead of a whole number?
There are two separate reasons for that: consistency and performance.
But before I get into that please note that you can easily get the desired behavior via extensions, e.g.:
inline val Date.time get() = getTime().toLong()
println(Date().time) // 1522757176433
Consistency. As you can see in the Date documentation page, it an external class. Which means it just describes an existing JavaScript API. Is it a good design decision to reuse it as it? Maybe not. But it has a benefit of being familiar to the JS folks. Changing the return type of a single function ruins that and makes the whole API quite inconsistent.
Performance. It is possible hide the original getTime and create a helper function instead. But keep in mind that in order to emulate Long Kotlin creates an object with 2 Number's. Creation, comparison, binary operations, storage - emulated Long's perform a lot worse than native JS Numbers.
Summing up. Changing the return type would make the API inconsistent and inefficient. If you value semantics over performance, just write a few helper functions.
P.S. I think the Date API will be redesigned at some point to make it possible to use it in multiplatform projects. But that's another story.
In kotlin use Date().time .It will return the long Values you will get whole number
val s= Date().time
print(s)
for example
val date = "01-02-2018 07:05:00.999"
val fmt = SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S") //parse date based your format
var myDate: Date? = null
try {
myDate = fmt.parse(date)
} catch (e: ParseException) {
e.printStackTrace()
}
println(myDate)
val timestamp = myDate!!.time //timestamp values in long only not double
println(timestamp)
I am new to salesforce and I know my question sounds silly. But I need someone to tell me the direction I should go.
My question is how can I convert string or object like this
{Start_time__C:"2014-07-24T20:55:00.000+0000"}
and this
{perDiem: true}
into salesforce object. And then I can use create function in remoteTK.
I am currently building custom app on salesforce1. In my visualforce page, I need to create new record, which has datetime, and boolean as its fields.
Thank you in advance!
I don't know much about the remoteTK but before you deep dive into it you might want to look into the "Remote Objects" from Spring'14. This seems to be the new hip / official way of doing remoting (which doesn't mean I'm saying rTK is bad!) and slightly easier to use.
https://salesforce.stackexchange.com/questions/33072/visualforce-remote-objects
https://developer.salesforce.com/blogs/developer-relations/2014/03/spring-14-using-visualforce-remote-objects-with-canjs.html
http://andyinthecloud.com/2014/01/22/spring14-visualforce-remote-objects-introduction/
http://www.salesforce.com/us/developer/docs/pages/Content/pages_remote_objects_example_extended.htm
The main difference between them seems to be that you could use rTK in a non-visualforce page as underneath it just relies on REST callouts. The remote objects use a special VF tag so it's VF-only.
In the end I think it won't matter much which library you'll use. Sample remote object code:
// Create work order line item
var workOrderLineItem = new SObjectModel.WorkOrderLineItem__c();
workOrderLineItem.set('Description__c', 'Answering the question');
workOrderLineItem.set('Hours__c', answer);
workOrderLineItem.set('WorkOrder__c', result[0]);
workOrderLineItem.create(function(error, result, event)
{
// Errors?
if(error!=null)
alert(error);
else
alert('Success');
});
vs. the sample from remoteTK:
var objectType = 'Account';
var fields = {'Name': 'salesforce.com', 'Description':'CRM'};
client.create(objectType , fields,
function(response) {
getAccounts(function() {
$j.mobile.pageLoading(true);
$j.mobile.changePage('#mainpage', "slide", true, true);
});
}, errorCallback);
So a JavaScript object with fields is being created in both cases. For Booleans you should be good sending 'true' or 'false' strings.
For dates you might have to experiment a bit. Generally I've been passing Unix timestamp (miliseconds since Jan 1 1970), this seemed to work OK for me in REST calls or Visualforce Remoting (by which I mean #RemoteAction stuff, yet another tool).
The RemoteTKController.writeFields() seems to be using Date.valueOf(someString) when casting. This means the format should be 'yyyy-MM-dd HH:mm:ss' which is close enough - check if it will work out of the box and remove the timezone part from your string if it causes problems? You could simplify your examples a lot by skipping the remote part and directly check in Developer Console or Execute Anonymous how the parser reacts to different dates you'll feed it.
There's another function that seems to use REST API instead of the controller. This one will just pass the payload to REST API's POST request. Looking at how it's built you should be fine just passing a real JavaScript Date object as value, the JSON.stringify call should figure out how to serialize that. If you really want to craft the string yourself - check the REST API guide. The dates should look like that and all remoteTK'create call does is make a request similar to this one
This is an old thread, but in case it helps someone I was able to get this working. The yyyy-MM-dd HH:mm:ss format was very close. All it needed was a 'T' between the date and time to be acceptable. From there is was just making sure that all components came through as two digits, and converting the date to UTC time. Here's my final Javascript function:
function ConvertDate(dtin){
var d = new Date(dtin);
var convertdate = d.getUTCFullYear() + '-' + ('0' + (d.getUTCMonth()+1)).slice(-2) + '-' + ('0' + d.getUTCDate()).slice(-2) +'T' + ('0' + d.getUTCHours()).slice(-2)+':'+('0' + d.getUTCMinutes()).slice(-2)+':'+d.getUTCSeconds()+'0';
return convertdate;
}
From there I could pass the converted date to the sObject function without error.
I am baffled. I have a "ready" function, from jQuery, which sets an HTML5 sessionStorage variable to the .valueOf() result of a new Date (as shown below). Somehow, though, the variable keeps refreshing and updating the time while my page is open. The sessionStorage variable doesn't even know it's a Date, it just stores the milliseconds, and the "ready" function is only called once at the beginning (I've checked using an alert window). There is no logic in my code to make this happen, but the value on the page stays up-to-date in real time. Any ideas?
// Initialize default date range
if (sessionStorage.minDate == null) {
d = new Date();
sessionStorage.minDate = (d.valueOf() - 172800000);
delete d;
}
if (sessionStorage.maxDate == null) {
d = new Date();
sessionStorage.maxDate = d.valueOf();
delete d;
}
UPDATE:
Still not fixed, but I've tried giving the milliseconds as a literal, and it still does the same thing. So it must have something to do with the fact that I'm creating a new Date later on using the millisecond count.
Any thoughts are much appreciated. I really have to get this working for work.
Apparently I was storing the number of milliseconds as a string, and wasn't parsing it back into an integer, so when I tried to create a new Date with it, javascript didn't know what to make of it and just created a Date with no parameters: the current date and time.
I need to create a countdown clock, that counts down the days, hours, minutes and seconds that are left to a date of my choice, using jQuery or Google App Engine (Python).
I have created a timer using JavaScript but for that I was using the system time.
I need to use the server time. Can anybody give me ideas to build a count down timer using the server UTC time.
I created a timer using Javascript,But in that i used system time.
If that JavaScript really serves your needs, then that JavaScript code could easily be made dynamic as well. In the code, wherever the current system time is initialized, simply insert your server time using your language of choice (Python). In other words: use your server language (Python) to output the script just as it is right now, except for replacing the part that initializes the current time.
In PHP, some pseudocode (not sure about the arguments of the Date() constructor) might look like, for example:
// my_countdown_script.php
[..]
var startTime = new Date( <?php echo time(); ?> );
[..]
Then, rather than including your JavaScript, you would be including the PHP file that inserts the server time like above:
<script type="text/javascript" src="my_countdown_script.php"></script>
The good thing is: this will work in any browser that supports the JavaScript you already created.
(In some later version, your JavaScript could include some initializers that allow you to set the current time after including the library in your HTML. That would allow the actual JavaScript library to be static, and thus to be cached by the browser.)
a good jquery plugin can be found here http://keith-wood.name/countdown.html
all you need to do then is pass in your new date from your scripting language php/asp.net by setting a variable on the page before the initialisation and updating the _calculatePeriods function to take that variable instead of the now one.
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery.countdown.js"></script>
<script type="text/javascript">
$(function () {
var servernow = new Date( <?php echo time(); ?> );
var austDay = new Date();
austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26);
$('#defaultCountdown').countdown({until: austDay});
$('#year').text(austDay.getFullYear());
});
</script>
from js/jquery.countdown.js
* Calculate the requested periods between now and the target time.
#param inst (object) the current settings for this instance
#param show (string[7]) flags indicating which periods are requested/required
#param now (Date) the current date and time
#return (number[7]) the current time periods (always positive)
by year, month, week, day, hour, minute, second */
_calculatePeriods: function(inst, show, now) {
// Find endpoints
inst._now = servernow;
Josh
You can reliably get server time from http://just-the-time.appspot.com/ -- an app engine app I made to help out a questioner on stack overflow, actually;-). Its simple code is opensourced at http://code.google.com/p/just-the-time/, and I could easily add the functionality you require (a page that, queried with the future date of your choice, returns days, hours, minutes and seconds to it, in some easily usable format) -- just let me know!
jQuery Timers is a plugin I've used in the past, and found to be very good.
Simply set two JavaScript variables to the current and target time for the countdown, and use a jQuery timer to update the "time remaining". If you want, you can add another time that re-synchronises the server and client times as well, every so often - though this probably isn't necessary.
why not simply use the UTC methods of the date object?
see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date
all local time methods have UTC counterparts
edit: this is meant to be used with his existing implementation in javascript.
If you really want to be sure you get the server time, do an XHR request (for anything) and check the Date header
So basically you need two things:
Page that displays the countdown time using the server time.
Client side updating of the time.
Render your time server side in something like this:
<span id="countdown" title="1245515631554">4 min. and 24 seconds</span>
Where the title is a timestamp of the current time that you can easily parse. You could also parse the text, but that requires more complex code.
Then add some Javascript that gets the time and updates the text every second. Setting a timeout that gets the date, updates it and sets the text.