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();
};
Related
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.
Oracle has depreciated nashorn and I use it in my apache ant build scripts.
Here is a short example;
try{load("nashorn:mozilla_compat.js");}catch(e){;}
importClass(java.io.File);
var sourceName = project.getProperty("build.source.dir") + "/" +project.getProperty("teiFile") + ".xml";
var targetName = project.getProperty("build.search.dir") + "/" + project.getProperty("teiFile") + ".xml";
var sourceFile = new File("", sourceName);
var targetFile = new File("", targetName);
var uptodate = targetFile.exists() && sourceFile.lastModified() < targetFile.lastModified();
var sourcePrefix = project.getProperty("teiFile");
if(!uptodate & !sourcePrefix.startsWith("G")) {
......
}
}
I've heard mentions of Rhino or graalVM as a replacement, but each seems to have a fairly long list of deficiencies.Suggestions for a library that is currently active and stable.
thanks, scott
GraalVM is currently active, stable, has a Nashorn compatibility mode.
You can run your ant scripts with GraalVM, and the JS engine is included by default. Or you can include GraalVM's JavaScript as a few dependencies and run on OpenJDK, which will be slower, and might be an untested combination of OpenJDK and GraalVM's JavaScript, but can also work.
I try to schedule a script using the 'Scheduled Tasks' in ML8. The documentation explains this a bit but only for xQuery.
Now I have a JavaScript file I'd like to schedule.
The error in the log file:
2015-06-23 19:11:00.416 Notice: TaskServer: XDMP-NOEXECUTE: Document is not of executable mimetype. URI: /scheduled/cleanData.js
2015-06-23 19:11:00.416 Notice: TaskServer: in /scheduled/cleanData.js [1.0-ml]
My script:
/* Scheduled script to delete old data */
var now = new Date();
var yearBack = now.setDate(now.getDate() - 65);
var date = new Date(yearBack);
var b = cts.jsonPropertyRangeQuery("Dtm", "<", date);
var c = fn.subsequence(cts.uris("", [], b), 1, 10);
while (true) {
var uri = c.next();
if (uri.done == true){
break;
}
xdmp.log(uri.value, "info"); // log for testing
}
Try the *.sjs extension (Server-side JavaScript).
The *.js extension can be used for static JavaScript resources to return to the client instead of executed on the server.
Hoping that helps,
I believe that ehennum found the issue for you (the extension - which is what the mime-type error is complaining about.
However, on the same subject, not all items in ML work quite as you would expect for Serverside Javascript. For example, using sjs as a target of a trigger is (or recently) did not work. So for things like that, it is also possible to wrap the sjs call inside of xqy using xdmp-invoke.
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'));
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()}`)
})