[英]How to get correcta date (from my timezone)?
I'm trying to build this code that would convert my current date into a URL path:我正在尝试构建此代码,将我当前的日期转换为 URL 路径:
var d = new Date();
var month = String(d.getMonth() + 1);
var day = String(d.getDate());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var year = String(d.getFullYear());
var path = year + "/" + month + "/" + day + "/"+ year + month + day + ".html";
resolve(path);
When run, the code works but it sometimes returns a URL from the following day .运行时,代码可以工作,但有时会从第二天返回 URL 。 I'm guessing this has to do with timezones: my timezone is -3 and I'm guessing the code runs UTC?
我猜这与时区有关:我的时区是-3 ,我猜代码运行 UTC? Does that make sense?
那有意义吗? How can I solve this?
我该如何解决这个问题?
Thank you very much for your help!非常感谢您的帮助!
You can take guesswork out of date calculation by getting UTC data.您可以通过获取 UTC 数据来消除过时的猜测。 Use something like this -
使用这样的东西 -
var d = new Date();
var month = String(d.getUTCMonth() + 1);
var day = String(d.getUTCDate());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var year = String(d.getUTCFullYear());
var path = year + "/" + month + "/" + day + "/"+ year + month + day + ".html";
resolve(path);
This way, all you calculations will be with respect with UTC and you'll always get exact date irrespective of your timezone or daylight saving.这样,您的所有计算都将与 UTC 相关,并且无论您的时区或夏令时如何,您都将始终获得准确的日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.