Parse.com how to include moment-timezone.js - javascript

I have a script in cloud code in parse.com. And I'm trying to use moment-timezone.js because I need to convert the timezone of my installation from string (ie "Europe/Paris") to a time offset from UTC (GMT).
My code so far imported from this question :
var moment = require('cloud/moment.js');
var tz = require('cloud/moment-timezone.js');
function toTimeZone(time, zone) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).tz(zone).format(format);
}
I have copied the latest moment.js and moment-timezone.js files from their website into my cloud directory.
Here is the error I get from log in cloud code :
Failed with: TypeError: Object Invalid date has no method 'tz'
at toTimeZone (main.js:6:30)
at query.find.success (main.js:19:17)
at Parse.js:2:10161
at e (Parse.js:2:8941)
at Parse.js:2:8390
at Array.forEach (native)
at Object.x.each.x.forEach [as _arrayEach] (Parse.js:1:661)
at c.extend.resolve (Parse.js:2:8341)
at e (Parse.js:2:9076)
at Parse.js:2:8390

According to Parse's documentation https://www.parse.com/docs/js/guide#cloud-code-modules-moment
You can try this:
var moment = require('cloud/moment');
var tz = require('cloud/moment-timezone');

Related

Date miscalculation on aws EBS server. It's running perfectly fine on local

There is always a miscalculation when deployed on aws server.
Context:
All the dates stored in mongoDB are in UTC format. And I want to convert the dates to IST before I export them in excel.
My code works perfectly fine on my local machine, but when deployed on server, it fails.
Here is an example that will help understand the issue.
const myDate = new Date('2022-12-21T18:41:18.384+00:00');
// The value of convertedDate should be 2022/12/21
// But, it for some reason returns - 2022/12/22
const convertedDate = myDate.toLocaleDateString('en-GB');
I also tried to user external library date-fns to handle the issue. Following is the sample code:
const zonedDate = utcToZonedTime(myDate, 'Asia/Kolkata');
// this is also - 2022/12/22
const convertedDate = formatInTimeZone(zonedDate, 'Asia/Kolkata', 'yyyy-MM-dd');
);
Another variation for date-fns that I tried was:
const zonedDate = utcToZonedTime(
new Date(myDate.valueOf() + myDate.getTimezoneOffset() * 60 * 1000),
'Asia/Kolkata',
);
// this is also - 2022/12/22
const convertedDate = formatInTimeZone(zonedDate, 'Asia/Kolkata', 'yyyy-MM-dd');
Please note that locally, everything works perfectly fine.
I also tried to use external library date-fns to handle the issue.
It seems you converted back-and-forth, or even converted twice (for double the timezone offset?). You should not need to use utcToZonedTime at all. Just pass your original myDate timestamp into formatInTimeZone:
const convertedDate = formatInTimeZone(myDate, 'Asia/Kolkata', 'yyyy-MM-dd');
locally, everything works perfectly fine
Change your system timezone to be that of the server (most likely UTC) and you should be able to reproduce the issue. For node.js, start it with the TZ environment variable.

timezone.js not working in zend framework 2

I am trying timezone conversion in javascript but I keep getting this in my console while using timezone.js :
warning : Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
error: GET http://exodo/tz/asia 404 (Not Found)
error : Uncaught TypeError: Cannot read property '1' of null
timezoneJS.timezone.zoneFileBasePath = 'tz';
timezoneJS.timezone.defaultZoneFile = ['asia', 'backward', 'northamerica', 'southamerica'];
timezoneJS.timezone.init({ async: false });
var dt = new window.timezoneJS.Date(new Date());
console.debug(dt.toString());
dt.setTimezone('America/Los_Angeles');
alert(dt);
prompt answers will be much appreciated
Thank you
Clearly you see that GET http://exodo/tz/asia 404 (Not Found) is failing.
You'll need the Olson time zone files -- timezoneJS.Date uses the raw Olson data to calculate timezone offsets. The Olson region files are simple, structured text data, which download quickly and parse easily. (They also compress to a very small size.)You can download from here
Put your directory of Olson files somewhere under your Web server root, and point timezoneJS.timezone.zoneFileBasePath to it. Then call the init function. Your code will look something like this:
timezoneJS.timezone.zoneFileBasePath = '/tz';
For more details read How to setup?
timezoneJS.timezone.zoneFileBasePath = '/tz';
timezoneJS.timezone.defaultZoneFile = ['asia', 'backward', 'northamerica', 'southamerica'];
var successFn = function (){
var dt = new window.timezoneJS.Date(new Date());
console.debug(dt.toString());
dt.setTimezone('America/Los_Angeles');
alert(dt);
};
timezoneJS.timezone.init({ callback: successFn });

Parsing Javascript Date to java.utils.date.Date

I have a service provide dates and i need process this in mi Android App
In my Node server:
server.send({'date': new Date() });
In my android app:
Date date = new Date(jsonObject.getString('date'));
this throws me a java.lang.IllegalArgumentException error
if a print in the android Log i get 2013-02-21T17:55:27.885Z how to handle this format
Store your Date as a long using
date.getTime()
making your calls look like this:
server.send({'date': new Date().getTime() });
and
Date date = new Date(jsonObject.getString('date'));

Date toLocaleDateString in node

When I use toLocaleDateString in browser it returns
n = new Date()
n.toLocaleDateString()
"2/10/2013"
but in node.js the format is completely different
n = new Date()
> n.toLocaleDateString()
'Sunday, February 10, 2013'
How to get the browser's format (mm/dd/yy) in node.js?
For me, the solution was to install an additional module full-icu for node js
full-icu-npm
And after in package.json insert:
{"scripts":{"start":"node --icu-data-dir=node_modules/full-icu YOURAPP.js"}}
or
In the current version of Node.js v10.9.0 is Internationalization Support.
To control how ICU is used in Node.js, you can configure options are available during compilation.
If the small-icu option is used you need to provide ICU data at runtime:
the NODE_ICU_DATA environment variable: 
env NODE_ICU_DATA=/some/directory node
the --icu-data-dir CLI parameter:
 node --icu-data-dir=/some/directory

I also found this broken in node.JS. For example, in node console, type
new Date().toLocaleDateString('en-GB')
it still displays US format. Using Werner's method above, you can override default Date.toLocaleDateString() behavior for your locale:
Date.prototype.toLocaleDateString = function () {
return `${this.getDate()}/${this.getMonth() + 1}/${this.getFullYear()}`;
};
UPDATE: 2021-12-01
Starting with Node.js v13.0.0, releases are now built with default full-icu support. So this shouldn't be a problem with later releases.
in node.JS you can not get browser's format.
Node.JS runs on Server-side.
You have to do date formatting before displaying it in browser at your client side JS framework.
Date.prototype.toLocaleDateString = function () {
var d = new Date();
return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
};

Does anyone know of a good JSON time server?

I need to obtain current time (from a credible source) using JSON. Precise time is mission-critical in my application so I cannot rely on the time of the device, even if it is only a second or two off.
EDIT: I am not as worried about 'precision' rather just so that several devices running the app have the same time.
As of Jan. 07th 2020 http://worldtimeapi.org/ is working fine. we can get current date and time details for specfic time-zone or ip address easily in either json format or plain text format.
http://worldtimeapi.org/api/timezone/America/Santiago
the above url will give you the current date and time details in json for "America/Santiago".
http://worldtimeapi.org/api/timezone/Asia/Kolkata
the above url will give you the current date and time details in json for "Asia/Kolkata".
Request the current time based on your public IP (as JSON):
$ curl "http://worldtimeapi.org/api/ip"
Note: by default, the API returns JSON. Adding a suffix of .txt to any API URL will return a plain-text response, which may be easier to parse on some systems.
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
// This is where you do whatever you want with the time:
alert(time);
});
from here
As of Sept. 12th 2015 http://www.timeapi.org/utc/now.json seems to be working.
{"dateString":"2015-09-12T23:15:56+01:00"}
More information here http://www.timeapi.org. It's hosted on Heroku and the source is on Github.
The worldtimeapi.org is working just fine. If you will be using Javascript:
const zone = 'Europe/Lisbon'
fetch('https://worldtimeapi.org/api/timezone/' + zone)
.then(r => r.json())
.then(r => {
// strip out timezone offset from datetime ISO string
const d = new Date(r.datetime.replace(/[+-]\d\d:\d\d$/, ''))
console.log(`Time now in ${zone}: ${d.getHours()}:${d.getMinutes()}`)
})

Categories

Resources