admin管理员组文章数量:1194548
i have written some code in javascript, and i want to use today's date as my file name, even i tried below code but it wont work for me.
filename=${`any_name_${new Date().toJSON().slice(0,10)}.zip
can anyone help me with it?
i have written some code in javascript, and i want to use today's date as my file name, even i tried below code but it wont work for me.
filename=${`any_name_${new Date().toJSON().slice(0,10)}.zip
can anyone help me with it?
Share Improve this question edited Jun 13, 2023 at 5:29 Carson 7,9482 gold badges56 silver badges54 bronze badges asked Apr 4, 2019 at 6:07 ChetanChetan 711 gold badge1 silver badge6 bronze badges 1 |4 Answers
Reset to default 15You can use template literals to accomplish this:
let filename = `any_name_${(new Date().toJSON().slice(0,10))}.zip`
console.log(`Add here ${filename}`);
You can use string concatenation:
var filename="any_name_" + new Date().toJSON().slice(0,10) + ".zip";
console.log(filename)
Output:
any_name_2019-04-04.zip
All the answers listed above just create a new Date, then look at the first part of it. However, JS Dates include timezones. As of writing this (1/6/22 @ 9PM in Eastern/US), if I run:
let filename = `any_name_${(new Date().toJSON().slice(0,10))}.zip`
console.log(`Add here ${filename}`);
it falsely gives me tommorows date (1/7/22). This is because Date() just looking at the first part of the date is ignoring the timezone.
A better way to do this that takes into account timezones is:
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
filename = mm + '-' + dd + '-' + yyyy + '.zip';
console.log(filename);
Adapted from here.
If you are using ES6 standards, we can use Template_literals Ref : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const filename = `any_name_${new Date().toJSON().slice(0,10)}.zip`;
本文标签: datetimehow to provide the date as filename using javascriptStack Overflow
版权声明:本文标题:datetime - how to provide the date as filename using javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738506888a2090586.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
filename = `any_name_${new Date().toJSON().slice(0,10)}.zip`
– adiga Commented Apr 4, 2019 at 6:12